0

I am trying to update the finalShapes state from initialShapes state and I am having a problem that finalShapes is not getting updated. I am making some changes in initalShapes state and then storing that manipulated data in finalShapes. Please tell me what am I doing wrong

this.state.initialShapes.map (sh => {
   var data = {};
   data.name = sh.name;
   data.x1 = sh.x;
   data.y1 = sh.y;
   data.x2 = sh.x + sh.width;
   data.y2 = sh.y + sh.height;
   this.setState ({finalShapes : [...this.state.finalShapes, data]});
});
5
  • 1
    this is not the way you work with setState are you trying to update the state on each iteration?
    – Sagiv b.g
    Commented Aug 7, 2018 at 14:05
  • You shouldn't be setting state on an iteration, but rather creating an object copy of the original state, acting on that copy to create your new state, and finally use one setState to set your final state to your edited copy Commented Aug 7, 2018 at 14:07
  • yes and what am i actually doing wrong?
    – Ketan
    Commented Aug 7, 2018 at 14:08
  • 1
    I would suggest to use the callback form of the setState if you want to access the previous state, like this.setState(prevState => { ... }).
    – peetya
    Commented Aug 7, 2018 at 14:09
  • ok but why we cannot do it this way?
    – Ketan
    Commented Aug 7, 2018 at 14:09

1 Answer 1

1

You do not update the state in a loop because it does not immediately update the state. It means that the next iteration of the loop will not see updated state.

ReactDocs:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

You can copy your inistialShapes and update the state once

var updatedShapes = this.state.initialShapes.map (sh => {
  var data = {};
  data.name = sh.name;
  data.x1 = sh.x;
  data.y1 = sh.y;
  data.x2 = sh.x + sh.width;
  data.y2 = sh.y + sh.height;

  return data;
});

this.setState ({finalShapes : updatedShapes });
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.