Skip to content

Apollo GraphQL useQuery hook triggered with old variables #9999

Open
@mjgasior

Description

@mjgasior

Intended outcome:
I am trying to make some reusable Apollo hooks and simplify the APIs with some encapsulation. So my idea is to have the useQuery hook inside of a custom hook (in current case I need actually the useLazyQuery hook). The variables that come to that useLazyQuery hook change, so I need to retrigger it using either main fetch, refetch or fetchMore functions. All of them do not work properly while triggered. Code provided below.

Actual outcome:

Code provided below. So there is a range of issues:

  • if I use refetch with the same id and a new date, the useLazyQuery calls for the something with the old date that was the initial one (why? no idea...)
  • if I replace refetch with fetchMore in refetchSomething, the call is actually done properly AT FIRST, but then there is a weird another call without ANY actual source in that hook which calls for something with old date
  • if I use getSomething in both loadSomething and refetchSomething it works like fetchMore where even tho the function was called only once, the Network tab shows two calls - one with old and second with new data.

How to reproduce the issue:

Here is a code snippet that does not work:

export const useGetSomething = () => {
  const [something, setSomething] = useState<Something>();
  const [getSomething, { data, refetch }] =
    useLazyQuery<GetSomethingHook>(GET_SOMETHING_QUERY, {
      fetchPolicy: 'no-cache',
    });

  useEffect(() => {
    if (data?.something) {
      setSomething(data.something);
    }
  }, [setSomething, data]);

  const loadSomething = useCallback(
    (id: string, date: Date) => {
      getSomething({
        variables: {
          args: {
            id,
            date,
          },
        },
      });
    },
    [getSomething],
  );

  const refetchSomething = useCallback(
    (id: string, date: Date) => {
      refetch({
        variables: {
          args: {
            id,
            date,
          },
        },
      }).then((result) => setSomething(result.data.something))
    },
    [setSomething, refetch],
  );

  return useMemo(() => {
    return {
      loadSomething,
      refetchSomething,
      something,
    };
  }, [something, loadSomething, refetchSomething]);
};

Versions

  System:
    OS: macOS 11.6.8
  Binaries:
    Node: 14.17.4 - /usr/local/bin/node
    Yarn: 1.22.18 - /usr/local/bin/yarn
    npm: 6.14.14 - /usr/local/bin/npm
  Browsers:
    Chrome: 104.0.5112.79
    Safari: 15.6
  npmPackages:
    @apollo/client: ^3.5.8 => 3.6.9 

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions