Skip to content

Commit

Permalink
Allow mutations to be reset
Browse files Browse the repository at this point in the history
Implements #8859
  • Loading branch information
brainkim committed Sep 30, 2021
1 parent e8ee939 commit 86c6690
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 2 deletions.
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
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 }];
}
1 change: 1 addition & 0 deletions src/react/types/types.ts
Original file line number Diff line number Diff line change
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

0 comments on commit 86c6690

Please sign in to comment.