Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use query hook react Apollo conditional call

I have been using react-apollo and the render prop approach.

This worked perfectly and my code looked something like this.

const App = () => {    const [player, setPlayer] = React.useState(null);    if (player) {      return (         <GetBroncosPlayerQuery variables={{ player }}>            {({ data }) => {               // do stuff here with a select box             }}          </GetBroncosPlayersQuery>      )    } } 

Now, if I try doing the same with the useQuery hook I get the following error, when my code looks like this:

const App = () => {    const [player, setPlayer] = React.useState(false);     if (isBroncos) {        const { data } = useQuery(GetBroncosPlayersQueryDocument, {          variables: { player }       });       // do stuff here    } } 

This gives an error that you cannot use a hook in a conditional statement. I then implemented useLazyQuery but this doesn't work either as after you call it once it behaves like useQuery, so it works the first time, but if the user changes a select dropdown to be empty again it breaks.

What is the best approach with the query hook to only call the query conditionally?

like image 352
peter flanagan Avatar asked Dec 26 '19 13:12

peter flanagan


People also ask

How do you query using Apollo Client?

Executing a query To run a query within a React component, call useQuery and pass it a GraphQL query string. When your component renders, useQuery returns an object from Apollo Client that contains loading , error , and data properties you can use to render your UI.

Does Apollo Client use React query?

Apollo Client's useQuery hook leverages React's Hooks API to bind a query to a component, enabling that component to render a query's results immediately. The useQuery hook encapsulates the logic for retrieving your data, tracking loading and error states, and updating your UI.

Can I use React query with GraphQL?

Because React Query's fetching mechanisms are agnostically built on Promises, you can use React Query with literally any asynchronous data fetching client, including GraphQL!


1 Answers

You should use skip option:

If skip is true, the query will be skipped entirely.

const isBroncos = getCondition();  const App = () => {   const [player, setPlayer] = React.useState(false);    const { data } = useQuery(GetBroncosPlayersQueryDocument, {     variables: { player },     skip: isBroncos   });    return !isBroncos && data && <>...</>; }; 
like image 195
Dennis Vash Avatar answered Oct 07 '22 17:10

Dennis Vash