-1

I have a list of file names populating in the UI. I'd like to add to this list on the front end (that.state.selectedReq.userUploads) after a file is uploaded to the API. Im creating a copy of what's in state with let userFiles = Object.assign and then want to iterate through the list of files to upload and add them to the copy of the array of what's in state. I then want to setState with the new array. However, I'm erroring out on the line userFiles.push(upload); and I'm not sure why.

var i = 100;
let userFiles = Object.assign({}, that.state.selectedReq.userUploads);
that.state.selectedFiles.forEach((x) => {
  let upload = {
    documentName: x.name,
    userUploadId: i,
    notes: "undefined"
   };
    i--;
    userFiles.push(upload);
  })

  that.setState({
    uploadFileInProgress: false,
    userUploads: userFiles
  })

Is there a better way to do what I'm trying to accomplish?

2 Answers2

3

Object.assign() returns an object, use spread operator to copy the array in state.

let userFiles = [...that.state.selectedReq.userUploads];
Junius L
  • 15,881
  • 6
  • 52
  • 96
0

.push() is a method of an array, not an object. Object.assign() will generate an object, that's why your code is erroring out.

If your state.selectedReq.userUploads is an array, you can do this:

let userFiles = that.state.selectedReq.userUploads.slice();
...
userFiles.push(upload);

If your state.selectedReq.userUploads is an object, you can do something like this:

let userFiles = Object.assign({}, that.state.selectedReq.userUploads);
...
userFiles[x.name] = upload;
technophyle
  • 7,972
  • 6
  • 29
  • 50