Skip to content

Commit

Permalink
Fix: Support useMutation client param passed to execute function (#9438)
Browse files Browse the repository at this point in the history
* Fix: Support useMutation client param passed to execute function

* Write tests for useMutation client passed as a param to execute function

* Update documentation to explicitly list `client` as an override option.

* Add changeset for #9438

---------

Co-authored-by: Jerel Miller <jerelmiller@gmail.com>
  • Loading branch information
dciesielkiewicz and jerelmiller committed Feb 20, 2023
1 parent 43be05f commit 52a9c8e
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/curly-countries-beg.md
@@ -0,0 +1,5 @@
---
'@apollo/client': patch
---

Ensure the `client` option passed to `useMutation`'s execute function is used when provided. Previously this option was ignored.
1 change: 1 addition & 0 deletions docs/shared/mutation-result.mdx
Expand Up @@ -29,6 +29,7 @@ A function to trigger the mutation from your UI. You can optionally pass this fu
* `refetchQueries`
* `update`
* `variables`
* `client`

Any option you pass here overrides any existing value for that option that you passed to `useMutation`.

Expand Down
31 changes: 31 additions & 0 deletions src/react/hooks/__tests__/useMutation.test.tsx
Expand Up @@ -496,6 +496,37 @@ describe('useMutation Hook', () => {
expect(result.current[1].client).toBeInstanceOf(ApolloClient);
});

it ('should call client passed to execute function', async () => {
const { result } = renderHook(
() => useMutation(CREATE_TODO_MUTATION),
{ wrapper: ({ children }) => (
<MockedProvider>
{children}
</MockedProvider>
)},
);

const link = mockSingleLink();
const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link
});

const mutateSpy = jest.spyOn(client, 'mutate').mockImplementation(
() => new Promise((resolve) => {
resolve({ data: CREATE_TODO_RESULT })
})
);

const createTodo = result.current[0];
await act(async () => {
await createTodo({ client });
});

expect(mutateSpy).toHaveBeenCalledTimes(1);
});

it('should merge provided variables', async () => {
const CREATE_TODO_DATA = {
createTodo: {
Expand Down
4 changes: 3 additions & 1 deletion src/react/hooks/useMutation.ts
Expand Up @@ -59,8 +59,10 @@ export function useMutation<
TCache
> = {}
) => {
const {client, options, mutation} = ref.current;
const {options, mutation} = ref.current;
const baseOptions = { ...options, mutation };
const client = executeOptions.client || ref.current.client;

if (!ref.current.result.loading && !baseOptions.ignoreResults && ref.current.isMounted) {
setResult(ref.current.result = {
loading: true,
Expand Down

0 comments on commit 52a9c8e

Please sign in to comment.