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 useReferenceManyFieldController does not debounce setFilters #9523

Merged
merged 4 commits into from
Dec 15, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import expect from 'expect';

import { testDataProvider } from '../../dataProvider/testDataProvider';
Expand All @@ -19,7 +19,7 @@ const ReferenceManyFieldController = props => {
describe('useReferenceManyFieldController', () => {
it('should set isLoading to true when related records are not yet fetched', async () => {
const ComponentToTest = ({ isLoading }: { isLoading?: boolean }) => {
return <div>isLoading: {isLoading.toString()}</div>;
return <div>isLoading: {isLoading?.toString()}</div>;
};
const dataProvider = testDataProvider({
getManyReference: () => Promise.resolve({ data: [], total: 0 }),
Expand Down Expand Up @@ -47,7 +47,7 @@ describe('useReferenceManyFieldController', () => {

it('should set isLoading to false when related records have been fetched and there are results', async () => {
const ComponentToTest = ({ isLoading }: { isLoading?: boolean }) => {
return <div>isLoading: {isLoading.toString()}</div>;
return <div>isLoading: {isLoading?.toString()}</div>;
};
const dataProvider = testDataProvider({
getManyReference: () =>
Expand Down Expand Up @@ -273,4 +273,50 @@ describe('useReferenceManyFieldController', () => {
);
});
});

it('should take only last change in case of a burst of setFilters calls (case of inputs being currently edited)', async () => {
let childFunction = ({ setFilters, filterValues }) => (
<input
aria-label="search"
type="text"
value={filterValues.q || ''}
onChange={event => {
setFilters({ q: event.target.value });
}}
/>
);
const dataProvider = testDataProvider();
const getManyReference = jest.spyOn(dataProvider, 'getManyReference');
render(
<CoreAdminContext dataProvider={dataProvider}>
<ReferenceManyFieldController
resource="authors"
source="id"
record={{ id: 123, name: 'James Joyce' }}
reference="books"
target="author_id"
>
{childFunction}
</ReferenceManyFieldController>
</CoreAdminContext>
);
const searchInput = screen.getByLabelText('search');

fireEvent.change(searchInput, { target: { value: 'hel' } });
fireEvent.change(searchInput, { target: { value: 'hell' } });
fireEvent.change(searchInput, { target: { value: 'hello' } });

await waitFor(() => new Promise(resolve => setTimeout(resolve, 600)));

// Called twice: on load and on filter changes
expect(getManyReference).toHaveBeenCalledTimes(2);
expect(getManyReference).toHaveBeenCalledWith('books', {
target: 'author_id',
id: 123,
filter: { q: 'hello' },
pagination: { page: 1, perPage: 25 },
sort: { field: 'id', order: 'DESC' },
meta: undefined,
});
});
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef } from 'react';
import get from 'lodash/get';
import isEqual from 'lodash/isEqual';
import lodashDebounce from 'lodash/debounce';

import { useSafeSetState, removeEmpty } from '../../util';
import { useGetManyReference } from '../../dataProvider';
Expand All @@ -15,6 +16,7 @@ import { useResourceContext } from '../../core';
export interface UseReferenceManyFieldControllerParams<
RecordType extends RaRecord = RaRecord
> {
debounce?: number;
filter?: any;
page?: number;
perPage?: number;
Expand Down Expand Up @@ -61,6 +63,7 @@ export const useReferenceManyFieldController = <
props: UseReferenceManyFieldControllerParams<RecordType>
): ListControllerResult<ReferenceRecordType> => {
const {
debounce = 500,
reference,
record,
target,
Expand Down Expand Up @@ -128,14 +131,29 @@ export const useReferenceManyFieldController = <
},
[setDisplayedFilters, setFilterValues]
);
const setFilters = useCallback(
(filters, displayedFilters) => {

// eslint-disable-next-line react-hooks/exhaustive-deps
const debouncedSetFilters = useCallback(
lodashDebounce((filters, displayedFilters) => {
setFilterValues(removeEmpty(filters));
setDisplayedFilters(displayedFilters);
setPage(1);
},
}, debounce),
[setDisplayedFilters, setFilterValues, setPage]
);

const setFilters = useCallback(
(filters, displayedFilters, debounce = true) => {
if (debounce) {
debouncedSetFilters(filters, displayedFilters);
} else {
setFilterValues(removeEmpty(filters));
setDisplayedFilters(displayedFilters);
setPage(1);
}
},
[setDisplayedFilters, setFilterValues, setPage, debouncedSetFilters]
);
// handle filter prop change
useEffect(() => {
if (!isEqual(filter, filterRef.current)) {
Expand Down
Loading