The following vanilla JS code is being used to export form data that has been converted to a blob, and saved to localstorage, out to a CSV file:
let ourData = localStorage.getItem("entry_list");
ourData = JSON.parse(ourData);
const titleKeys = Object.keys(ourData[0])
const refinedData = []
refinedData.push(titleKeys)
ourData.forEach(item => {
refinedData.push(Object.values(item))
})
let csvContent = ''
refinedData.forEach(row => {
csvContent += row.join(',') + 'n'
})
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8,' })
const objUrl = URL.createObjectURL(blob)
const link = document.createElement('a')
link.setAttribute('href', objUrl)
link.setAttribute('download', 'export.csv')
link.textContent = 'export'
document.querySelector('span.export').appendChild(link)
To initiate this export I use the following link on the main page:
<span class="export"></span></div>
The problem I have is that the link will only display if there is data in the blob / localstorage. For example, if user data has been entered into the form, and the page is refreshed, the link will display. If there is no user data entered into the form, the link is not displayed.
I want the link text "export" to display always, whether there is user data present or not, and I definitely need to avoid forcing the user to refresh after the enter data into a blank form.
I hope this makes sense and if you can tell me where I am going wrong, or why this behavior is occurring, I would be very grateful. I think I may have to create the empty blob first…?
Thank in advance.
2
Answers
I resolved this myself. One lined needed to be fixed to resolve the problem:
to
The behavior you’re encountering is likely due to the fact that when there is no data in local storage (localStorage.getItem("entry_list") returns null), the code does not execute further to create the link element. To always display the "export" link, you can modify your code to conditionally create the link element regardless of whether there is data in local storage.