Skip to content

Instantly share code, notes, and snippets.

@FennyFatal
Last active January 13, 2022 20:34
Show Gist options
  • Save FennyFatal/1c7e510666d87ae1218df77fb7d59be4 to your computer and use it in GitHub Desktop.
Save FennyFatal/1c7e510666d87ae1218df77fb7d59be4 to your computer and use it in GitHub Desktop.
Apollo wrapper to make skip: true act kinda the same in @apollo/client 3.5+
import { useQuery as useQueryReal } from '@apollo/client';
import _ from 'lodash';
import {
useEffect,
useCallback,
useRef,
} from 'react';
export const useQuery = (query, {
skip = false,
variables = {},
...options
} = {}, ...args) => {
const wasCalled = useRef(false);
const localVariables = useRef(variables);
const execute = (
wasCalled
&& localVariables.current
) || !skip;
const { refetch: refetchReal, ...queryStuff } = useQueryReal(query, {
...(options ?? {}),
variables: localVariables.current ?? variables,
skip: !execute,
}, ...args);
useEffect(() => {
if (
variables && Object.keys(variables).length > 0
&& !_.isEqual(variables, localVariables.current)
) localVariables.current = variables;
}, [...Object.values(variables ?? {})]);
const refetch = useCallback(async (variableInputs, ...refetchArgs) => {
if (variableInputs) localVariables.current = variableInputs;
wasCalled.current = true;
const result = await refetchReal(variableInputs, ...refetchArgs);
wasCalled.current = !skip;
return result;
}, [refetchReal, variables]);
return { ...queryStuff, refetch };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment