Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  183] [ 1]  / answers: 1 / hits: 20461  / 4 Years ago, thu, december 26, 2019, 12:00:00

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?


More From » reactjs

 Answers
30

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 && <>...</>;
};

[#51357] Friday, December 13, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
theron

Total Points: 168
Total Questions: 93
Total Answers: 94

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
;