0

I am trying to open a zip file, grab certain elements from it, push them into an array, and use that array to render a list of components in react. The problem I'm having is that anything I do to nameArray inside of this for loop isn't recognized outside of it.

isUploadPressed(props) {
if(props === true) {
  let zip = new JSZip(); 

  JSZip.loadAsync(this.state.zipFile).then(function (zip) {
    var listOfFiles;

    for (let zipEntry of Array.from(zip)) {
      var nameArray = new Array;
      nameArray.push(zipEntry.split('/').pop());
    }
    alert("NameArray: " + nameArray.pop());
    nameArray.map((element) => listOfFiles.push(<li><File fileName={element}/></li>)) 
    return listOfFiles;
  });

}

}

Unhandled Rejection (TypeError): Cannot read property 'pop' of undefined

Austin L
  • 3
  • 2

1 Answers1

0

you should declare the var nameArray = new Array; outside of the for loop so you can call the variable.

isUploadPressed(props) {
if(props === true) {
  let zip = new JSZip(); 

  JSZip.loadAsync(this.state.zipFile).then(function (zip) {
    var listOfFiles;
    var nameArray = new Array;

    for (let zipEntry of Array.from(zip)) {
      nameArray.push(zipEntry.split('/').pop());
    }

    alert("NameArray: " + nameArray.pop()); // Now you should be able to call nameArray properly
    nameArray.map((element) => listOfFiles.push(<li><File fileName={element}/></li>)) 
    return listOfFiles;
  });

}

I suggest you to read and understand more about scope here: What is the scope of variables in JavaScript?

Jee Mok
  • 6,157
  • 8
  • 47
  • 80