0
scriptWriter = (data:ItemType) => {
    let id = data.id
    console.log(this.state.items.map(el => el.id === id ? data : el)) //#1
    this.setState({
        items: this.state.items.map(el => el.id === id ? data : el)
    })
    console.log(this.state.items) //#2
}

this is my code. i'm trying to change element inside state array. but #1 code's result and #2's result are diffrent. I want to change this.state.item to #1 result. is there a any solution?

Roharui
  • 100
  • 7

1 Answers1

0

That is because setState is asynchronous in nature, use a callback to log state value which will be invoked after state is update:

this.setState({
    items: this.state.items.map(el => el.id === id ? data : el)
  },
  () =>  console.log(this.state.items)
);
Dipen Shah
  • 25,562
  • 1
  • 32
  • 58