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

Some quick features we might shove into 3.5 release #8875

Merged
merged 4 commits into from
Oct 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,15 @@
- Make `cache.batch` return the result of calling the `options.update` function. <br/>
[@benjamn](https://github.com/benjamn) in [#8696](https://github.com/apollographql/apollo-client/pull/8696)

- The `NetworkError` and `ErrorResponse` types have been changed to align more closely. <br/>
[@korywka](https://github.com/korywka) in [#8424](https://github.com/apollographql/apollo-client/pull/8424)

### React Refactoring

#### Improvements (due to [@brainkim](https://github.com/brainkim) in [#8875](https://github.com/apollographql/apollo-client/pull/8875)):
- The `useLazyQuery` function now returns a promise with the result.
- The `useMutation` result now exposes a method which can be reset.

#### Bug Fixes (due to [@brainkim](https://github.com/brainkim) in [#8596](https://github.com/apollographql/apollo-client/pull/8596)):

- The `useQuery` and `useLazyQuery` hooks will now have `ObservableQuery` methods defined consistently.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
{
"name": "apollo-client",
"path": "./dist/apollo-client.min.cjs",
"maxSize": "27.85 kB"
"maxSize": "28.0 kB"
}
],
"engines": {
Expand Down
38 changes: 38 additions & 0 deletions src/react/hooks/__tests__/useLazyQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -506,4 +506,42 @@ describe('useLazyQuery Hook', () => {
expect(result.current[1].loading).toBe(false);
expect(result.current[1].data).toEqual({ hello: 'from link' });
});

it('should return a promise from the execution function which resolves with the result', async () => {
const query = gql`{ hello }`;
const mocks = [
{
request: { query },
result: { data: { hello: 'world' } },
delay: 20,
},
];
const { result, waitForNextUpdate } = renderHook(
() => useLazyQuery(query),
{
wrapper: ({ children }) => (
<MockedProvider mocks={mocks}>
{children}
</MockedProvider>
),
},
);

expect(result.current[1].loading).toBe(false);
expect(result.current[1].data).toBe(undefined);
const execute = result.current[0];
const mock = jest.fn();
setTimeout(() => mock(execute()));

await waitForNextUpdate();
expect(result.current[1].loading).toBe(true);

await waitForNextUpdate();
expect(result.current[1].loading).toBe(false);
expect(result.current[1].data).toEqual({ hello: 'world' });

expect(mock).toHaveBeenCalledTimes(1);
expect(mock.mock.calls[0][0]).toBeInstanceOf(Promise);
expect(await mock.mock.calls[0][0]).toEqual(result.current[1]);
});
});
55 changes: 55 additions & 0 deletions src/react/hooks/__tests__/useMutation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,61 @@ describe('useMutation Hook', () => {

expect(fetchResult).toEqual({ data: CREATE_TODO_DATA });
});

it('should be possible to reset the mutation', async () => {
const CREATE_TODO_DATA = {
createTodo: {
id: 1,
priority: 'Low',
description: 'Get milk!',
__typename: 'Todo',
},
};

const mocks = [
{
request: {
query: CREATE_TODO_MUTATION,
variables: {
priority: 'Low',
description: 'Get milk.',
}
},
result: {
data: CREATE_TODO_DATA,
}
}
];

const { result, waitForNextUpdate } = renderHook(
() => useMutation<
{ createTodo: Todo },
{ priority: string, description: string }
>(CREATE_TODO_MUTATION),
{ wrapper: ({ children }) => (
<MockedProvider mocks={mocks}>
{children}
</MockedProvider>
)},
);

const createTodo = result.current[0];
let fetchResult: any;
await act(async () => {
fetchResult = await createTodo({
variables: { priority: 'Low', description: 'Get milk.' },
});
});

expect(fetchResult).toEqual({ data: CREATE_TODO_DATA });
expect(result.current[1].data).toEqual(CREATE_TODO_DATA);
setTimeout(() => {
result.current[1].reset();
});

await waitForNextUpdate();
expect(result.current[1].data).toBe(undefined);
});
});

describe('ROOT_MUTATION cache data', () => {
Expand Down
30 changes: 26 additions & 4 deletions src/react/hooks/useLazyQuery.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DocumentNode } from 'graphql';
import { TypedDocumentNode } from '@graphql-typed-document-node/core';
import { useCallback, useState } from 'react';
import { useCallback, useEffect, useState } from 'react';

import {
LazyQueryHookOptions,
Expand All @@ -26,21 +26,36 @@ export function useLazyQuery<TData = any, TVariables = OperationVariables>(
options?: LazyQueryHookOptions<TData, TVariables>
): QueryTuple<TData, TVariables> {
const [execution, setExecution] = useState<
{ called: boolean, options?: QueryLazyOptions<TVariables> }
{
called: boolean,
options?: QueryLazyOptions<TVariables>,
resolves: Array<(result: LazyQueryResult<TData, TVariables>) => void>,
}
>({
called: false,
resolves: [],
});

const execute = useCallback<
QueryTuple<TData, TVariables>[0]
>((executeOptions?: QueryLazyOptions<TVariables>) => {
let resolve!: (result: LazyQueryResult<TData, TVariables>) => void;
const promise = new Promise<LazyQueryResult<TData, TVariables>>(
(resolve1) => (resolve = resolve1),
);
setExecution((execution) => {
if (execution.called) {
result && result.refetch(executeOptions?.variables);
}

return { called: true, options: executeOptions };
return {
called: true,
resolves: [...execution.resolves, resolve],
brainkim marked this conversation as resolved.
Show resolved Hide resolved
options: executeOptions,
};
});

return promise;
}, []);

let result = useQuery<TData, TVariables>(query, {
Expand All @@ -51,6 +66,13 @@ export function useLazyQuery<TData = any, TVariables = OperationVariables>(
fetchPolicy: execution.called ? options?.fetchPolicy : 'standby',
skip: undefined,
});
useEffect(() => {
const { resolves } = execution;
if (!result.loading && resolves.length) {
setExecution((execution) => ({ ...execution, resolves: [] }));
resolves.forEach((resolve) => resolve(result));
}
}, [result, execution]);

if (!execution.called) {
result = {
Expand All @@ -66,7 +88,7 @@ export function useLazyQuery<TData = any, TVariables = OperationVariables>(
for (const key of EAGER_METHODS) {
const method = result[key];
result[key] = (...args: any) => {
setExecution({ called: true });
setExecution((execution) => ({ ...execution, called: true }));
return (method as any)(...args);
};
}
Expand Down
9 changes: 7 additions & 2 deletions src/react/hooks/useMutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export function useMutation<
): MutationTuple<TData, TVariables, TContext, TCache> {
const client = useApolloClient(options?.client);
verifyDocumentType(mutation, DocumentType.Mutation);
const [result, setResult] = useState<MutationResult>({
const [result, setResult] = useState<Omit<MutationResult, 'reset'>>({
called: false,
loading: false,
client,
Expand Down Expand Up @@ -122,9 +122,14 @@ export function useMutation<
});
}, [client, options, mutation]);

const reset = useCallback(() => {
setResult({ called: false, loading: false, client });
}, []);

useEffect(() => () => {
ref.current.isMounted = false;
}, []);

return [execute, result];

return [execute, { reset, ...result }];
}
3 changes: 2 additions & 1 deletion src/react/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export interface QueryLazyOptions<TVariables> {
export type LazyQueryResult<TData, TVariables> = QueryResult<TData, TVariables>;

export type QueryTuple<TData, TVariables> = [
(options?: QueryLazyOptions<TVariables>) => void,
(options?: QueryLazyOptions<TVariables>) => Promise<LazyQueryResult<TData, TVariables>>,
LazyQueryResult<TData, TVariables>
];

Expand Down Expand Up @@ -149,6 +149,7 @@ export interface MutationResult<TData = any> {
loading: boolean;
called: boolean;
client: ApolloClient<object>;
reset(): void;
}

export declare type MutationFunction<
Expand Down