Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setState() in loop using spread operator

I'm trying to set new values for several fields in nested object in state using spread operator in loop, but it works only for last field.

I have an array "formFields" with names of fields which values I want to overwrite. I use map() to compare each element in array with field in state and switch it's value to "true". But it change value only for the last field in array - "comment".

constructor() {
    super();
    this.state = {
        fields: {
            time: false,
            date: false,
            quantity: false,
            comment: false,
        },
    }
}

getFormFields() {
    const formFields = ["time", "quantity", "comment"];
    formFields.map(item => {
        this.setState({
            ...this.state.fields,
            [item]: true
        })
    });
}

What should I do to overwrite values for all the fields I want?

like image 756
Elena Mykhailiuk Avatar asked May 29 '26 19:05

Elena Mykhailiuk


1 Answers

Since you are changing state in a loop, and each state you set contains the original item with only changed, the latest change overrides the previous one. Instead, create a new state object with the change, and then setState the object once:

getFormFields() {
  const formFields = ["time", "quantity", "comment"];
  this.setState(formFields.reduce((r, item) => ({
    ...r,
    [item]: true
  }), {}));
}

btw - If the fields you want to set to true are always the same, you can create the object manually, and set it:

getFormFields() {
  this.setState({
      time: true,
      quantity: true,
      comment: true,
  });
}
like image 176
Ori Drori Avatar answered May 31 '26 10:05

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!