0

I wants to change grade object of state using dynamic key. Below is my code

state = {
            id1: {
                name: 'XYZ',
                grade: {
                    science: 'A',
                    maths: 'C',
                },
            },
            id2: {
                name: 'ABC',
                grade: {
                    science: 'A+',
                    maths: 'A+',
                },
            },
}

I tried couple of things but couldn't found successful result.

updateGrade(gradeObj, dyamicKey) { // dyamicKey will be id1, id2
    this.setState({
        [dyamicKey]: {
            ... dyamicKey.grade,
            grade: gradeObj,
        },
    });
}

updateGrade(gradeObj, dyamicKey) { // dyamicKey will be id1, id2
    this.setState({
        [dyamicKey[grade]]: gradeObj,
    });
}
JiteshW
  • 2,195
  • 4
  • 32
  • 61

2 Answers2

4
this.setState(prevState => ({
  [dyamicKey]: {
    ...prevState[dyamicKey],
    grade: gradeObj,
  },
}));
Roy Wang
  • 11,112
  • 2
  • 21
  • 42
0

FYI: this topic was extensively cover here, and even is recommended not to use nested states, according to this answer.

As an extra comment to the first answer and for the ones to come, if you have two or more nested values in your state and you want to update a single nested value, you could do the following:

this.setState(prevState => ({
  [dynamicKey]: {
  ...prevState[dynamicKey],
  grade: { 
    ...prevState[dynamicKey].grade,
    science: "Z"
  },
}));

Or, if the dynamic key is related to a specific attribute:

this.setState(prevState => ({
  id1: {
  ...prevState.id1,
  grade: { 
    ...prevState.id1.grade,
    [dynamicKey]: "Z"
  },
}));

One or more dynamic keys can be used and the spread operator can be used for each nested level (although the code will start to look ugly/dirty with this approach).