4

I have the below function that adds attachments from an <input type="file" multiple /> to a parent's state.

That works fine until the user wants to add another attachment/s, the new attachment/s override the existing ones, how can I have the new attachments be added to the existing attachments array?

handleAddAttachments = fileList => {
  this.props.handleChange('attachments', Array.from(fileList));
};

I tried that but it doesn't seem to work.

handleAddAttachments = fileList => {
  const { attachments } = this.props.ticket;
  this.props.handleChange('attachments', [...attachments, fileList]);
};

The parent handleChange function:

makeHandleChange = (pageName, change) => {
  this.setState({
    ticket: { ...this.state.ticket, [pageName]: change },
  });
};
user3378165
  • 6,546
  • 17
  • 62
  • 101
  • If you ```console.log([...attachments, fileList])``` do you see the expected result? – sigmus May 28 '19 at 08:31
  • @sigmus, no, let's say I first added 3 attachments and then added a 4th one, I see a `[{"0": {},"1": {},"2": {}}{"0": {}}]` instead of `[{},{},{},{}]` that I would expected to see. – user3378165 May 28 '19 at 08:35

1 Answers1

1

In your second version you are missing the Array.from() part. The change from a fileInput is not directly an array, so the spread operator does not work.

This should do the trick:

handleAddAttachments = fileList => {
  const { attachments } = this.props.ticket;
  this.props.handleChange('attachments', [...attachments, ...Array.from(fileList)]);
};

For further information why it is not an array, you can find some information here: Why isn't the FileList object an array?

Thanks @sigmus, I added the missing spread to the Array.from()

Nicolas Gehlert
  • 2,626
  • 18
  • 39
  • I have tried that too, the result is first `[[{},{},{},{}]]` instead of `[{},{},{},{}]`, then when I add a new attachment the result is: `[[{},{},{},{}],[{}]]`instead of `[{},{},{},{},{}]` – user3378165 May 28 '19 at 08:47
  • 1
    And if you also spread Array.from, like ```[...attachments, ...Array.from(fileList)]```? – sigmus May 28 '19 at 08:58
  • @NicolasGehlert please update your question so I can accept it – user3378165 May 28 '19 at 09:19