Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
UseQuery with variables:{} param from useEffect

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:

  1. In useEffect
    1. get {id} from the router
    2. trigger getUserFromId(id) with that id
    3. setUser() with db response
  2. Run the query
    1. get user from state and pass it into variables:{} for query
    2. run the query

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!