I want Update nested object in react context api
this is my context
import { createContext, useState } from "react";
const TeethInfoContext = createContext();
export function TeethInfoProvider({ children }) {
const [teethInfo, setTeethInfo] = useState({
11: {
mesial: true,
distal: false,
incisal: false,
},
12: {
mesial: true,
distal: false,
incisal: false,
},
13: {
mesial: true,
distal: false,
incisal: false,
},
return (
<TeethInfoContext.Provider
value={{ teethInfo, cordinates, drawShape, setTeethInfo }}
>
{children}
</TeethInfoContext.Provider>
);
}
export default TeethInfoContext;
how can update single value in this object like {11: mesial } set to false
thanks
i tried many ways to update
tried this function in children
function drawMesial() {
setTeethInfo({ ...teethInfo, mesial: teethInfo[11].mesial });
}
not working
and tried
function drawShape(param, id) {
setTeethInfo({ ...teethInfo, param: !teethInfo[id].param });
}
in context but didnt work
2
Answers
The React documentation suggests using an updater function to change the state based on the previous state.
You should create a new function to update the values but be careful with the mutability.
Looks here:
https://legacy.reactjs.org/docs/optimizing-performance.html#the-power-of-not-mutating-data
https://legacy.reactjs.org/docs/optimizing-performance.html#the-power-of-not-mutating-data
To set
{11: mesial}
to false, you would call:Here is what the code will look like.
Of course, you could create a method to modify the complete tooth:
}