1

How do I wait for a useQuery hook to finish when a useEffect hook is trigered?

I have a pretty complicated functional component and I am triggering a useEffect hook with its dependancies being from a grandparent functional component. The useQuery hook and the useEffect hook both work successfully. However, when the useEffect hook is triggered it does not wait for the query to complete before carrying out the function which is called by useEffect.

Failed Solutiuon #1: I tried using async and await but when you use return await you are "uwrapping" a promise only for the value to be "wrapped" again (since you are inside an async function), so it is redundant.

Faild Solution #2. I could use .then() but the function that needs to be called will be within the .then() and how would I call it from the useEffect.

const data = useQuery('lists', ...{promise is returned)..);
const functionToBeCalled = () => { //uses data }
useEffect(() => {
        if (grandparent prop) { functionToBeCalled()}
    }, [grandparent prop]);

Any support will be really appreciated.

1 Answer 1

6

That code doesn't look quite right to me - useQuery doesn't return data directly, you have to destructure it. Without seeing the code as it's actually written, I think the answer you're chasing is that you need to add the data as a dependency to your effect:

const { data } = useQuery(/* ... */);

const functionThatUsesData = () => log('DATA:', data);

useEffect(() => {
    if (!(grandparentProp && data)) return;
    functionThatUsesData();
}, [grandparentProp, data]);

Sign up to request clarification or add additional context in comments.

1 Comment

I tried that and it works. thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.