i have created state by using React Context but when i try to update propert of state in child components it do not work, sometime syntax error some time logical error, can anyone please help me ?
in App.js
const [car, setCar] = useState();
<AuthContext.Provider value={{ car, setCar }}>
<NavigationContainer>
{car ? (
<CustomerHomeStackNavigator />
) : (
<Splash></Splash>
)}
</NavigationContainer>
</AuthContext.Provider>
in child component i want to update its offer property but it not working, i did like this but not worked
const carContext = React.createContext();
carContext.setCar.data.offer= "1000"
car sate have this data object
Object {
"aud": "The_Aud",
"data": Object {
"address": "delhi",
"area": "delhi",
"city": "delhi",
"contactnumber": "122222222222",
"offer": "20000000"
},
"exp": 1654602892,
"iat": 1654599292,
"iss": "The_claim",
"nbf": 1654599302,
"stakeHolder": "owner",
}
CodePudding user response:
setCar is not object, is a function. you can take value with useContext
, can update an object like below
const {car,setCar}= useContext(AuthContext);
setCar(prev => {...prev,data : {...prev.data,offer:"10000"}})
option 2:
var updatedCar = {...car};
updatedCar.data.offer = "1500";
setCar(updatedCar)
CodePudding user response:
setCar
it is function, so for update you must call function instead of simple
variable assignment.
Next for getting context you must use useContext
hook or static field context
if you are going to use class components. You can't use createContext
for get context value, it is only for create context object.
const { car, setCar } = useContext(AuthContext)
// ...
setCar(data)
See doc for more details https://reactjs.org/docs/context.html#updating-context-from-a-nested-component