FileSaver and zipJs Issue

33 views Asked by At

I have a modal that contains a button to separate my json data into different .json files and download them as a zip file.

I have the code below

function createZipFile(jsonData) {
    const zip = new JSZip();
    let files = {};
    jsonData.map((obj) =>
        Object.entries(obj).forEach(([key, value]) => {
            files[key] = Object.assign(...value);
        })
    );

    Object.entries(files).forEach(([key, value]) => {
        zip.file(${key}.json, JSON.stringify(value));
    });

    zip.generateAsync({ type: "blob" }).then(function (content) {
        // see FileSaver.js

        saveAs(content, {{projectTitle}}.zip);



    });
}

The code works fine and downloads the zip file successfully and the content is alright as well but when I close the modal and open it up again the zip file is not getting downloaded anymore, although it will be generated. The saveAs function is not triggering anymore . How may I fix this issue?

1

There are 1 answers

0
Teq Teq On

I could solve that issue

due to using the saveAs function from FileSaver.js within an asynchronous function. The saveAs function can only be called once, and subsequent calls may not work as expected.

The code below works fine

function createZipFile(jsonData) {
  const zip = new JSZip();
  let files = {};

  jsonData.map((obj) =>
    Object.entries(obj).forEach(([key, value]) => {
      files[key] = Object.assign(...value);
    })
  );

  Object.entries(files).forEach(([key, value]) => {
    zip.file(`${key}.json`, JSON.stringify(value));
  });

  zip.generateAsync({ type: 'blob' }).then(function (content) {
    // Create a temporary anchor element
    const link = document.createElement('a');
    link.href = URL.createObjectURL(content);
    link.download = '{{projectTitle}}.zip';
    link.style.display = 'none';

    // Add the anchor element to the document body
    document.body.appendChild(link);

    // Trigger the download
    link.click();

    // Remove the anchor element from the document body
    document.body.removeChild(link);
  });
}