Chia Yi
Chia Yi

Reputation: 562

setState doesn't update as expected

I'm a ReactJS beginner and this is my code below.

for (var key in getContentState){
    var string=getContentState[key]
    if(highlighted_cols.includes(Object.keys(string).toString())){
        arr=Object.values(string)
        this.setState({
            uniqueValues : arr
        },()=>{
            console.log("update")
            console.log(this.state.uniqueValues)
        })
    }
}

getContentState is an object which looks like screenshot of getContentState

I am trying to update uniqueValues everytime the key is matched with highlighted_cols. highlighted_cols is selected by user which in this case either species or farmer as you can see in getContentState.

It works fine when user select only one column (species or farmer). But when user selects multiple columns (species and farmer), it displays unique values for farmer only.

Upvotes: 1

Views: 73

Answers (2)

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

It looks like you are overriding the state (uniqueValues) key by updating the state inside the for loop. Have you tried to update the state only once?

Something like:

let result = []
for (var key in getContentState) {
  var string = getContentState[key]

  if (highlighted_cols.includes(Object.keys(string).toString())) {
    result = [
      ...result,
      Object.values(string),
    ]
    // or result.push(Object.values(string))
}

this.setState({
  uniqueValues : result
}, () => {
  console.log('update')
  console.log(this.state.uniqueValues)
})

Upvotes: 1

wezzy
wezzy

Reputation: 5935

I think that it's due to some react optimizations, or, more simply, the state is changed before the rendering is complete and the ending state doesn't contains the first value. You should not call setState() inside a for loop.

I suggest you to prepare the new object that will update the state and then call to setState() after the for loop is concluded.

Hope this helps

Upvotes: 0

Related Questions