Home > Enterprise >  react js - prevstate does not remember the previous state?
react js - prevstate does not remember the previous state?

Time:04-14

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.

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

Thank's in advance for any help.

CodePudding user response:

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
    }
  }
});
  • Related