Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react js – prevstate does not remember the previous state?

I am trying to access and update a variable (state) that is inside an array inside a nested element; see below.

interface IState {
  fields: {
    values: ['val1', 'val2'],
}}

I am using the following function to update the element in the array :

  onStateSubArrValueChange = (
    newValue: string | Date | boolean,
    fieldName: string,
    index:number,
  ) => {
    this.setState(prevState =>{
      return{
        ...prevState,
        fields: {
          ...prevState.fields,
          [fieldName]:{
            [index]:newValue
          }
        }
      }
    });
  };

I used this on several elements, when I changed them, the last value is visible in the state variable, that was last updated. If I write the array in a file, I can see the last update but not any other previous one. The syntax seems correct, TypeScript does not raise any alarms… The value does get written down in the element (IState.fields.values[I]). I tried to look on StackOverflow and on other websites but I cannot seems to find why this is not working. I also tried different forms and location for loading …prevState. I also used the normal spread for state, but obviously that is not keeping the previous state.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 this.setState({
   fields: {
     ...this.state.fields,
     [fieldName]:{
       [index]:newValue
     }
   }
 });

Thank’s in advance for any help.

>Solution :

It should be something like this I think

this.setState(prevState =>{
  return{
    ...prevState,
    fields: {
      ...prevState.fields,
      values: [...prevState.fields.values, newValue]
    }
  }
});

or this below because question is not really clear to me

this.setState(prevState =>{
  const tempValues = prevState.fields.values;
  tempValues[indexToUpdate] = value
  return{
    ...prevState,
    fields: {
      ...prevState.fields,
      values: tempValues
    }
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading