Skip to content

Commit

Permalink
Merge pull request #6886 from marmelab/fix-usemutation-options
Browse files Browse the repository at this point in the history
Fix useMutation not considering returnPromise option
  • Loading branch information
djhi committed Nov 19, 2021
2 parents 0b49b94 + 37f8476 commit 58e7ba3
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
43 changes: 43 additions & 0 deletions packages/ra-core/src/dataProvider/useMutation.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Mutation from './Mutation';
import { CoreAdmin, Resource } from '../core';
import { renderWithRedux } from 'ra-test';
import { DataProviderContext } from '.';
import useMutation from './useMutation';

describe('useMutation', () => {
it('should pass a callback to trigger the mutation', () => {
Expand Down Expand Up @@ -264,4 +265,46 @@ describe('useMutation', () => {
const result = await promise;
expect(result).toMatchObject({ data: { foo: 'bar' } });
});

it('should return a response when returnPromise option is set at definition and the query is passed al callTime', async () => {
const MutationComponent = ({ query = undefined, options, children }) =>
children(...useMutation(query, options));
const dataProvider = {
mytype: jest.fn(() => Promise.resolve({ data: { foo: 'bar' } })),
};

let response = null;
const myPayload = {};
const { getByText, dispatch } = renderWithRedux(
<DataProviderContext.Provider value={dataProvider}>
<MutationComponent options={{ returnPromise: true }}>
{(mutate, { loading }) => (
<button
className={loading ? 'loading' : 'idle'}
onClick={async () =>
(response = await mutate({
type: 'mytype',
resource: 'myresource',
payload: myPayload,
}))
}
>
Hello
</button>
)}
</MutationComponent>
</DataProviderContext.Provider>
);
const buttonElement = getByText('Hello');
fireEvent.click(buttonElement);
const action = dispatch.mock.calls[0][0];
expect(action.type).toEqual('CUSTOM_FETCH');
expect(action.payload).toEqual(myPayload);
expect(action.meta.resource).toEqual('myresource');
await waitFor(() => {
expect(buttonElement.className).toEqual('idle');
});

expect(response).toMatchObject({ data: { foo: 'bar' } });
});
});
8 changes: 7 additions & 1 deletion packages/ra-core/src/dataProvider/useMutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,13 @@ const mergeDefinitionAndCallTimeParameters = (
type: callTimeQuery.type,
resource: callTimeQuery.resource,
payload: callTimeQuery.payload,
options: sanitizeOptions(callTimeOptions),
options: options
? merge(
{},
sanitizeOptions(options),
sanitizeOptions(callTimeOptions)
)
: sanitizeOptions(callTimeOptions),
};
};

Expand Down

0 comments on commit 58e7ba3

Please sign in to comment.