reactjsapollo-clientreact-apolloreact-typescriptreact-apollo-hooks

What is the better way to handle conditional useQuery calls in apollo client react?


We have this query with according types:

const GET_ITEM = gql`
  query GetItem($itemId: Int!) {
    item(where: { itemId: $itemId }) {
      name
    }
  }
`;
type TQuery = { item: string };
type TVariables = { itemId: number };

What is the better approach to fetch our item conditionally in the component? First option:

function Item({ itemId }: { itemId: number | undefined }) {
  const { data } = useQuery<TQuery, TVariables>(GET_ITEM, {
    variables: { itemId: itemId ?? 0 },
    skip: itemId === undefined,
  });

  return <>{data?.item}</>;
}

Second option:

function Item({ itemId }: { itemId: number | undefined }) {
  const [fetchItem, { data }] = useLazyQuery<TQuery, TVariables>(GET_ITEM);

  useEffect(() => {
    if (itemId !== undefined) {
      fetchItem({ variables: { itemId } });
    }
  }, [itemId, fetchItem]);

  return <>{data?.item}</>;
}

Which approach is correct/better and why?


Solution

  • If it depends on whether that itemId is present, go the skip route.

    The useLazyQuery + useEffect will trigger an extra rerender and is more complicated.