react-apollo-hooks icon indicating copy to clipboard operation
react-apollo-hooks copied to clipboard

Question: How to call second useQuery with a variable: response from first useQuery

Open MarioKrstevski opened this issue 5 years ago • 3 comments

How would you call two useQuery hooks, but the second one should wait for the first one to return some data because we need to pass that data as a variable for the second one.

When I was using render props with react-apollo, this is not a problem because the second (nested) Query component won't start fetching until the first one returns data.

Any ideas?

MarioKrstevski avatar Jul 22 '19 18:07 MarioKrstevski

You'd have to make another component that uses the second hook.

The first component would look something like this..

function ComponentWithFirstHook() {
 const {data, loading, error} = useQuery(QUERY)

 if (loading) return <Loader />
 if (error) return <Error />
 return (
   <ComponentWithSecondHook params={data.params} />
 )
}

JClackett avatar Jul 22 '19 18:07 JClackett

I think no need to create extra component, you can use useEffect, observe if first query returned data and then trigger second query. Render component in case all data arrived. Sth like :

function ComponentOne() {
 const {data, loading, error} = useQuery(QUERY_ONE)
 const [fetchSecondQueryData, {data: secondQueryData, loading: secondQueryLoading, error: secondQueryError}] = useLazyQuery(QUERY_TWO)

 useEffect(() => {
  if(data[checkIfExistsExactKeyYouWantToPassSecondQuery]) {
    fetchSecondQueryData({variables: { params: data.params }})
  }
 }, [data])

 if (loading || secondQueryLoading) return <Loader />
 if (error || secondQueryError) return <Error />
 return (
   <div>Display data</div>
 )
}

Or it might be be even better to create custom hook and handle whole logic inside it.

vanoMekantsishvili avatar Dec 11 '20 11:12 vanoMekantsishvili

Anyone have an example doing this with custom hook? I'm attempting to do something very similar except I would like to use the results from other hooks inside another hook. Problem I'm running into is first load of hooks that I would like to use results from are empty due to loading.. which results in the parent hook getting called with empty values.

Any suggestions or examples doing something similar is appreciated.

michaelbdavid avatar May 03 '22 20:05 michaelbdavid