Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: setState after unmount #7655

Merged
merged 11 commits into from
Feb 9, 2021
17 changes: 15 additions & 2 deletions src/react/hooks/utils/useBaseQuery.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useContext, useEffect, useReducer, useRef } from 'react';
import { useContext, useEffect, useReducer, useRef, RefObject } from 'react';
import { DocumentNode } from 'graphql';
import { TypedDocumentNode } from '@graphql-typed-document-node/core';

Expand All @@ -13,13 +13,26 @@ import { useDeepMemo } from './useDeepMemo';
import { OperationVariables } from '../../../core';
import { getApolloContext } from '../../context';

const useMounted = (): RefObject<boolean> => {
const mounted = useRef(false);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
}
}, []);
return mounted;
}

export function useBaseQuery<TData = any, TVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: QueryHookOptions<TData, TVariables>,
lazy = false
) {
const context = useContext(getApolloContext());
const [tick, forceUpdate] = useReducer(x => x + 1, 0);
const mounted = useMounted();
const [tick, forceUpdateUnsafe] = useReducer(x => x + 1, 0);
const forceUpdate = () => mounted.current ? forceUpdateUnsafe() : undefined;
const updatedOptions = options ? { ...options, query } : { query };

const queryDataRef = useRef<QueryData<TData, TVariables>>();
Expand Down