trojanowski / react-apollo-hooks

Use Apollo Client as React hooks
MIT License
2.42k stars 110 forks source link

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

Open MarioKrstevski opened 5 years ago

MarioKrstevski commented 5 years ago

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?

JClackett commented 5 years ago

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} />
 )
}
vanoMekantsishvili commented 3 years ago

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.

michaelbdavid commented 2 years ago

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.