'UseQuery Async Variables Issue
I am trying to make a simple useQuery request but the variables which I am dependent on for the request are being loaded asynchronously. My apologies in advance for the kind of messy variable names.
Currently I have a useQuery hook which I want to function like this.
const { id } = router.query;
let userDbAddress;
useEffect(() => {
async function getUsernameEthAddress() {
userDbAddress = await getUserAddressFromUsernameDb(id);
}
getUsernameEthAddress();
return () => (mountedRef.current = false);
}, [router.isReady]);
let userVariables = {
where: {
id: userDbAddress,
},
};
const { loading, error, data } = useQuery(GET_USER_DATA, {
variables: userVariables, //<<<I AM NULL (because running before async useEffect completes!)
});
if (loading) return null;
if (error) return <Error statusCode={404} />;
const myData = data?.myData;
My problem is that the asynchronous is in the ordering of my data. The userDbAddress is null when the useQuery is called and I am not sure when I can best pass it into the variables parameter for my query. I am not sure if this is the proper use case for useLazyQuery? I want my query to run on page render just after the useEffect hook runs so that I can wire up the userDbAddress variable to pass into the useQuery hook.
Thanks for taking the time:)
And happy to clarify if the question is too messy/wordy
Solution 1:[1]
This is react-query right?
If so, there is a 3rd parameter to set options for the query. Just add { enabled: false } as an option in that 3rd parameter and the query won't fire off immediately. Secondly, pull the refetch function from the object returned from useQuery(). Then, once userVariables has valid data (you can create a useEffect() for this), you can call refetch() and your expected flow work work now.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mr_Antivius |
