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<DeleteButton mutationOptions> ignores meta parameter #8023

Merged
merged 7 commits into from
Aug 4, 2022
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
11 changes: 6 additions & 5 deletions docs/Buttons.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,11 +244,11 @@ export const PostList = () => (

![Bulk Delete button](./img/bulk-delete-button.png)

| Prop | Required | Type | Default | Description |
| ------------ | -------- | --------------- | ------------------ | ----------------------------------- |
| `label` | Optional | `string` | 'ra.action.delete' | label or translation message to use |
| `icon` | Optional | `ReactElement` | `<DeleteIcon>` | iconElement, e.g. `<CommentIcon />` |
| `exporter` | Optional | `Function` | - | Override the List exporter function |
| Prop | Required | Type | Default | Description |
| --------------------| -------- | --------------- | ------------------ | ---------------------------------------------------|
| `label` | Optional | `string` | 'ra.action.delete' | label or translation message to use |
| `icon` | Optional | `ReactElement` | `<DeleteIcon>` | iconElement, e.g. `<CommentIcon />` |
| `mutationOptions` | Optional | `object` | null | options for react-query `useMutation` hook |
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The description isn't entirely accurate, as react-query's options cannot contain a meta key. In fact, you should probably add an example explaining how to set the meta parameter.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a meta option in useMutation. It is of type Record<string, unknown> when ours is any though.


### `<FilterButton>`

Expand Down Expand Up @@ -277,6 +277,7 @@ Delete the current record after a confirm dialog has been accepted. To be used i
| `confirmContent` | Optional | `ReactNode` | 'ra.message.delete_content' | Message or React component to be used as the body of the confirm dialog |
| `redirect` | Optional | `string | false | Function` | 'list' | Custom redirection after success side effect |
| `translateOptions` | Optional | `{ id?: string, name?: string }` | {} | Custom id and name to be used in the confirm dialog's title |
| `mutationOptions` | Optional | | null | options for react-query `useMutation` hook |
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same


{% raw %}
```jsx
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React from 'react';
import expect from 'expect';
import { MemoryRouter, Route, Routes } from 'react-router';
import { fireEvent, screen, render, waitFor } from '@testing-library/react';

import { testDataProvider } from '../../dataProvider';
import { CoreAdminContext } from '../../core';
import useDeleteWithConfirmController, {
UseDeleteWithConfirmControllerParams,
} from './useDeleteWithConfirmController';

describe('useDeleteWithConfirmController', () => {
it('should call the dataProvider.delete() function with the meta param', async () => {
let receivedMeta = null;
const dataProvider = testDataProvider({
delete: jest.fn((ressource, params) => {
receivedMeta = params?.meta?.key;
return Promise.resolve({ data: params?.meta?.key });
}),
});

const MockComponent = () => {
const { handleDelete } = useDeleteWithConfirmController({
record: { id: 1 },
resource: 'posts',
mutationMode: 'pessimistic',
mutationOptions: { meta: { key: 'metadata' } },
} as UseDeleteWithConfirmControllerParams);
return <button onClick={handleDelete}>Delete</button>;
};

render(
<MemoryRouter>
<CoreAdminContext dataProvider={dataProvider}>
<Routes>
<Route path="/" element={<MockComponent />} />
</Routes>
</CoreAdminContext>
</MemoryRouter>
);

const button = await screen.findByText('Delete');
fireEvent.click(button);
waitFor(() => expect(receivedMeta).toEqual('metadata'), {
fzaninotto marked this conversation as resolved.
Show resolved Hide resolved
timeout: 1000,
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@ const useDeleteWithConfirmController = <RecordType extends RaRecord = any>(
redirect: redirectTo,
mutationMode,
onClick,
mutationOptions,
mutationOptions = {},
} = props;
const { meta: mutationMeta, ...otherMutationOptions } = mutationOptions;
const resource = useResourceContext(props);
const [open, setOpen] = useState(false);
const notify = useNotify();
Expand All @@ -95,7 +96,11 @@ const useDeleteWithConfirmController = <RecordType extends RaRecord = any>(
event.stopPropagation();
deleteOne(
resource,
{ id: record.id, previousData: record },
{
id: record.id,
previousData: record,
meta: mutationMeta,
},
{
onSuccess: () => {
setOpen(false);
Expand Down Expand Up @@ -128,7 +133,7 @@ const useDeleteWithConfirmController = <RecordType extends RaRecord = any>(
);
},
mutationMode,
...mutationOptions,
...otherMutationOptions,
}
);
if (typeof onClick === 'function') {
Expand All @@ -137,8 +142,9 @@ const useDeleteWithConfirmController = <RecordType extends RaRecord = any>(
},
[
deleteOne,
mutationMeta,
mutationMode,
mutationOptions,
otherMutationOptions,
notify,
onClick,
record,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React from 'react';
import expect from 'expect';
import { MemoryRouter, Route, Routes } from 'react-router';
import { fireEvent, screen, render, waitFor } from '@testing-library/react';

import { testDataProvider } from '../../dataProvider';
import { CoreAdminContext } from '../../core';
import useDeleteWithUndoController, {
UseDeleteWithConfirmControllerParams,
} from './useDeleteWithConfirmController';

describe('useDeleteWithUndoController', () => {
it('should call the dataProvider.delete() function with the meta param', async () => {
let receivedMeta = null;
const dataProvider = testDataProvider({
delete: jest.fn((ressource, params) => {
receivedMeta = params?.meta?.key;
return Promise.resolve({ data: params?.meta?.key });
}),
});

const MockComponent = () => {
const { handleDelete } = useDeleteWithUndoController({
record: { id: 1 },
resource: 'posts',
mutationMode: 'undoable',
mutationOptions: { meta: { key: 'metadata' } },
} as UseDeleteWithConfirmControllerParams);
return <button onClick={handleDelete}>Delete</button>;
};

render(
<MemoryRouter>
<CoreAdminContext dataProvider={dataProvider}>
<Routes>
<Route path="/" element={<MockComponent />} />
</Routes>
</CoreAdminContext>
</MemoryRouter>
);

const button = await screen.findByText('Delete');
fireEvent.click(button);
waitFor(() => expect(receivedMeta).toEqual('metadata'), {
timeout: 1000,
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ const useDeleteWithUndoController = <RecordType extends RaRecord = any>(
record,
redirect: redirectTo = 'list',
onClick,
mutationOptions,
mutationOptions = {},
} = props;
const { meta: mutationMeta, ...otherMutationOptions } = mutationOptions;
const resource = useResourceContext(props);
const notify = useNotify();
const unselect = useUnselect(resource);
Expand All @@ -63,7 +64,11 @@ const useDeleteWithUndoController = <RecordType extends RaRecord = any>(
event.stopPropagation();
deleteOne(
resource,
{ id: record.id, previousData: record },
{
id: record.id,
previousData: record,
meta: mutationMeta,
},
{
onSuccess: () => {
notify('ra.notification.deleted', {
Expand Down Expand Up @@ -93,7 +98,7 @@ const useDeleteWithUndoController = <RecordType extends RaRecord = any>(
);
},
mutationMode: 'undoable',
...mutationOptions,
...otherMutationOptions,
}
);
if (typeof onClick === 'function') {
Expand All @@ -102,7 +107,8 @@ const useDeleteWithUndoController = <RecordType extends RaRecord = any>(
},
[
deleteOne,
mutationOptions,
mutationMeta,
otherMutationOptions,
notify,
onClick,
record,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ import {
useTranslate,
useUnselectAll,
useSafeSetState,
RaRecord,
DeleteManyParams,
} from 'ra-core';

import { Confirm } from '../layout';
import { Button, ButtonProps } from './Button';
import { BulkActionProps } from '../types';
import { UseMutationOptions } from 'react-query';

export const BulkDeleteWithConfirmButton = (
props: BulkDeleteWithConfirmButtonProps
Expand All @@ -29,9 +32,11 @@ export const BulkDeleteWithConfirmButton = (
icon = defaultIcon,
label = 'ra.action.delete',
mutationMode = 'pessimistic',
mutationOptions = {},
onClick,
...rest
} = props;
const { meta: mutationMeta, ...otherMutationOptions } = mutationOptions;
const { selectedIds } = useListContext(props);
const [isOpen, setOpen] = useSafeSetState(false);
const notify = useNotify();
Expand All @@ -41,7 +46,7 @@ export const BulkDeleteWithConfirmButton = (
const translate = useTranslate();
const [deleteMany, { isLoading }] = useDeleteMany(
resource,
{ ids: selectedIds },
{ ids: selectedIds, meta: mutationMeta },
{
onSuccess: () => {
refresh();
Expand Down Expand Up @@ -73,6 +78,7 @@ export const BulkDeleteWithConfirmButton = (
setOpen(false);
},
mutationMode,
...otherMutationOptions,
}
);

Expand Down Expand Up @@ -141,13 +147,20 @@ const sanitizeRestProps = ({
'resource' | 'icon' | 'mutationMode'
>) => rest;

export interface BulkDeleteWithConfirmButtonProps
extends BulkActionProps,
export interface BulkDeleteWithConfirmButtonProps<
RecordType extends RaRecord = any,
MutationOptionsError = unknown
> extends BulkActionProps,
ButtonProps {
confirmContent?: React.ReactNode;
confirmTitle?: string;
icon?: ReactElement;
mutationMode: MutationMode;
mutationOptions?: UseMutationOptions<
antoinefricker marked this conversation as resolved.
Show resolved Hide resolved
RecordType,
MutationOptionsError,
DeleteManyParams<RecordType>
> & { meta?: any };
}

const PREFIX = 'RaBulkDeleteWithConfirmButton';
Expand Down
19 changes: 16 additions & 3 deletions packages/ra-ui-materialui/src/button/BulkDeleteWithUndoButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ import {
useUnselectAll,
useResourceContext,
useListContext,
RaRecord,
DeleteManyParams,
} from 'ra-core';

import { Button, ButtonProps } from './Button';
import { BulkActionProps } from '../types';
import { UseMutationOptions } from 'react-query';

export const BulkDeleteWithUndoButton = (
props: BulkDeleteWithUndoButtonProps
Expand All @@ -23,8 +26,10 @@ export const BulkDeleteWithUndoButton = (
label = 'ra.action.delete',
icon = defaultIcon,
onClick,
mutationOptions = {},
...rest
} = props;
const { meta: mutationMeta, ...otherMutationOptions } = mutationOptions;
const { selectedIds } = useListContext(props);

const notify = useNotify();
Expand All @@ -36,7 +41,7 @@ export const BulkDeleteWithUndoButton = (
const handleClick = e => {
deleteMany(
resource,
{ ids: selectedIds },
{ ids: selectedIds, meta: mutationMeta },
{
onSuccess: () => {
notify('ra.notification.deleted', {
Expand Down Expand Up @@ -66,6 +71,7 @@ export const BulkDeleteWithUndoButton = (
refresh();
},
mutationMode: 'undoable',
...otherMutationOptions,
}
);
if (typeof onClick === 'function') {
Expand Down Expand Up @@ -95,10 +101,17 @@ const sanitizeRestProps = ({
...rest
}: Omit<BulkDeleteWithUndoButtonProps, 'resource' | 'icon'>) => rest;

export interface BulkDeleteWithUndoButtonProps
extends BulkActionProps,
export interface BulkDeleteWithUndoButtonProps<
RecordType extends RaRecord = any,
MutationOptionsError = unknown
> extends BulkActionProps,
ButtonProps {
icon?: ReactElement;
mutationOptions?: UseMutationOptions<
antoinefricker marked this conversation as resolved.
Show resolved Hide resolved
RecordType,
MutationOptionsError,
DeleteManyParams<RecordType>
> & { meta?: any };
}

const PREFIX = 'RaBulkDeleteWithUndoButton';
Expand Down