I am trying to set my Context API object as below in one of functional components as below;
I set it 3 times in the same component as below;
let tmpObj = {
user1: props.user1,
user2: props.user2
}
// Called 2nd. Below is NOT retained
setMyContextApiObj({
...myContextApiObj,
tmpObj
});
//Called 3rd. This one is retained
setMyContextApiObj({
...myContextApiObj,
myValFromStorage: myValFromStorage
});
//Called 1st. This one is retained
setMyContextApiObj({
...myContextApiObj,
myPref: myPref
});
However, for some reason, I only get the myValFromStorage and myPref values once I am out of this component and not the tmpObj one. Not sure why that value is not getting retained in the Context API
You have two options for solving this problem:
1-Make all the desired changes to your context value in a single call to the setMyContextApiObj function. This involves summarizing all the changes into one function call:
setMyContextApiObj({
...myContextApiObj,
tmpObj,
myValFromStorage: myValFromStorage,
myPref: myPref
});
2-Instead of explicitly passing an object to the setMyContextApiObj function's input, pass a function to it that returns the new context state value. This way, React will understand that there is a dependency between all the new values and will execute all the calls in order, after the previous call and the previous context value has been set:
setMyContextApiObj((c) => {
return {
...c,
tmpObj
}
})
setMyContextApiObj((c) => {
return {
...c,
myValFromStorage: myValFromStorag
}
})
setMyContextApiObj((c) => {
return {
...c,
myPref: myPref
}
})
this is an example to explain how it work: codesandbox