use query hook react Apollo conditional call

∥☆過路亽.° 提交于 2020-06-11 21:23:31

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/59489097/use-query-hook-react-apollo-conditional-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!