skip to Main Content

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


  1. Chosen as BEST ANSWER

    I resolved this myself. One lined needed to be fixed to resolve the problem:

    const titleKeys = Object.keys(ourData[0]); 
    

    to

    const titleKeys = Object.keys(ourData[0] || {});
    

  2. 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.

    // Retrieve data from local storage
    let ourData = localStorage.getItem("entry_list");
    ourData = ourData ? JSON.parse(ourData) : []; // Check if data exists, otherwise initialize as empty array
    
    // Create CSV content
    const titleKeys = Object.keys(ourData[0] || {}); // Use empty object if no data exists to avoid errors
    const refinedData = [];
    refinedData.push(titleKeys);
    
    ourData.forEach(item => {
      refinedData.push(Object.values(item));  
    });
    enter code here
    let csvContent = '';
    
    refinedData.forEach(row => {
      csvContent += row.join(',') + 'n';
    });
    
    // Create Blob and link only if there is data or if it's an empty array
    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';
    
    // Always append the link to the span, regardless of data presence
    document.querySelector('span.export').appendChild(link);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search