Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until context value has been set | React Hooks

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?

like image 674
Martin Nordström Avatar asked Oct 15 '22 16:10

Martin Nordström


1 Answers

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);
    }
};
like image 194
Shubham Khatri Avatar answered Oct 19 '22 13:10

Shubham Khatri