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,
    });
}

2 Answers 2

4
this.setState(prevState => ({
  [dyamicKey]: {
    ...prevState[dyamicKey],
    grade: gradeObj,
  },
}));
Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.