I am trying to run a useQuery hook with variable:{} parameter but the data I am passing into variables is coming from a useEffect Hook.
I know I am unable to pass in the useQuery into useEffect so I have been passing in the data from useEffect into a state variable and then passing that into the useQuery.
This actually works okay and does not crash the app but it does hit the error hook about 3 times before it actually does work
Here is how my code looks
const router = useRouter();
const { id } = router.query;
const [user, setUser] = useState({});
const [profileTypeA, setProfileTypeA] = useState(false);
let userData
useEffect(() => {
async function getUser() {
if (!router.isReady) return;
const userDb = await getUserFromDb(id);
if (userDb === undefined) {
return <Error statusCode={404} />;
} else {
setUser(userDb?.data?.payload);
if (userDb.data.payload.type === 'A') setProfileTypeA(true);
}
}
getUser();
return () => {
consola.success('Cleanup profile page');
};
}, [router.isReady]);
if (profileTypeA) {
const { loading, error, data } = useQuery(QUERY_FOR_USER_TYPE_A, {
variables: { id: user?.userId },
});
if (loading) return null;
if (error) return <Error statusCode={404} />;
userData = data?.moreData;
}
My problem is with the variables is this the best way to pass the dynamic data to variables?
I realize that is a flaw to be honest I was going to deal with that later (which maybe I am underestimating). But even if I take the useQuery out of the if block then the error is still there.
My logic is intended as follows:
I think that my problem is that the useEffect is running after my useQuery so the user i am trying to get from the useEffect is still empty but I am not sure how and where else I can run all the logic I have in my useEffect to get the data i need to pass into the variables:{}
Thank you