Search code examples
react-nativesetstate

update nested value of state using dynamic key


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

Solution

  • this.setState(prevState => ({
      [dyamicKey]: {
        ...prevState[dyamicKey],
        grade: gradeObj,
      },
    }));