How do I wait until context value has been set?
I had a problem where I couldn't get the value from my context, so when I needed it I always got the initial value, ""
. So now I have a useEffect
in my component,
useEffect(() => {
if (posContext.activePaymentTabId) {
console.log("poscontext i useeffect", posContext); <-- can see my value here now
// handlePaymentResponse(true, "GODKÄNT");
}
}, [posContext.activePaymentTabId]);
I set my value in this function:
const makeCardPayment = async () => {
posContext.handleSetActivePaymentTabId(); // <-- Here I set my value that I need later
try {
const res = await functionA();
return functionB(res.foo);
} catch (error) {}
};
But in functionB
where my value is needed:
const functionB = (foo) => {
if (foo) {
setTimeout(() => {
console.log("calling...", posContext); // <-- Now my value is back to it's initial
}, 3500);
}
};
So, what other options do I have when I want to have access to my values directly from my context?
Since context value change is reflected only on initial render, you could pass a callback function to the setter which returns the updated value and pass the context value to functionB
.
const makeCardPayment = () => {
posContext.handleSetActivePaymentTabId(async function(updatedContext) {
try {
const res = await functionA();
return functionB(res.foo, posContext);
} catch (error) {
}
});
};
const functionB = (foo, posContext) => {
if (foo) {
setTimeout(() => {
console.log("calling...", posContext); // <-- Now my value is back to it's initial
}, 3500);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With