this.setState is not pushing items into an array when using a for loop in React

by Matt Brody   Last Updated October 10, 2019 02:26 AM

I want to push these multiple file objects into an array I created in my state. But when I run this code, only the last one is set to state. Why is this happening and how can I fix it?

If I console.log imageChosen inside the for loop it returns only empty arrays for each iteration. Is it not updating state fast enough?

state = { imageChosen: [] };    

fileSelectedHandler = event => {
    for (let i = 0; i < event.target.files.length; i++) {
      this.setState({ imageChosen: [ ...this.state.imageChosen, event.target.files[i]] })
      console.log(event.target.files[i])
    }
  }
Tags : reactjs


Answers 2


using setState() with for-loop is not recomendable.

fileSelectedHandler = event => {
    let tmp = [];
    for (let i = 0; i < event.target.files.length; i++) {
      tmp.push(event.target.files[i]);
      // this.setState({ imageChosen: [ ...this.state.imageChosen, event.target.files[i]] })
      console.log(event.target.files[i])
    }
    this.setState(tmp);
  }
zynkn
zynkn
October 10, 2019 02:22 AM

But when I run this code, only the last one is set to state.

The problem is you are not using the previous state when looping.

this.setState(prevState => {
   imageChosen: [
     ...prevState.imageChosen,
     event.target.files[i]
   ]
})

Recommended: However, you can just append the files directly without the loop.

this.setState({
  imageChosen: [
    ...this.state.imageChosen,
    ...event.target.files
  ]
})
Joseph D.
Joseph D.
October 10, 2019 02:25 AM

Related Questions


Updated November 07, 2018 13:26 PM

Updated June 21, 2015 23:11 PM

Updated October 20, 2018 07:26 AM

Updated August 07, 2017 01:26 AM