0

Tried to update a state. Somehow the setState isn't working..

this is the function and state:


state = {
    security: {
      0: { id: "54321", name: "test1"}
      1: { id: "98765", name: "test2"}
              }
}

removeSecInState = (security) => () => {

        var temp = Object.assign({}, this.state.security)
        var temp1 = Object.values(temp)
        var index = temp1.findIndex(id => id.id ===  security.id) //getIndex

        delete temp[0]

        this.setState({security: temp},() =>  {
            console.log(temp, "inside");
            console.log(this.state.security, "inside1")

        })
    }
console.log(temp, "inside") =  
security: {
      1: { id: "98765", name: "test2"}
              }
console.log(this.state.security, "inside1") = 
security: {
      0: { id: "54321", name: "test1"}
      1: { id: "98765", name: "test2"}
              }

somehow, state is not updated to be the same with temp, always goes back to the previous state

1 Answers1

-1

It seems that you have not included the this keyword before state, also you should

Try this

this.state = {
    security: {
      0: { id: "54321", name: "test1"}
      1: { id: "98765", name: "test2"}
              }
}

Also you should try to refactor the code a little bit

Maybe like this

this.state = {
    security: [
      { id: "54321", name: "test1"},
      { id: "98765", name: "test2"}
              ]
}

removeSecInState(sec) {
    this.setState({
        security: this.state.security.filter(item => item.id !== sec.id)
    })
}

Ignacio Elias
  • 365
  • 1
  • 7
  • OP uses class property. Also if you were right won't it cause a completely different issue then? :) – Yury Tarabanko Apr 16 '20 at 11:14
  • thanks for the answer sir, will update if it works. :bow: – Denis Villamero Apr 16 '20 at 11:21
  • Well it depends on where you have declared the state, if it's declared inside its constructor it should be with the this keyword – Ignacio Elias Apr 16 '20 at 11:21
  • But from the code it is almost obvious that state has been declared within class body as a property. Same for the `removeSecInState`. – Yury Tarabanko Apr 16 '20 at 11:23
  • @YuryTarabanko is right, it doesn't seem to make any difference. Still, the error is in the implementation of ```removeSecInState```. i suggest changing the security to an array of objects instead of an object with nested objects first, and then changing the ```removeSecInState``` as it's written in the answer – Ignacio Elias Apr 16 '20 at 11:33
  • okay mister, will try to do that. thanks again you guys :bow: – Denis Villamero Apr 16 '20 at 11:43