Skip to content

Commit

Permalink
Merge pull request #9359 from marmelab/fix-useGetList-big-data-cache-…
Browse files Browse the repository at this point in the history
…update

Fix `useGetList` optimistic cache update leads to ui freeze when too many records are returned
  • Loading branch information
fzaninotto authored Oct 16, 2023
2 parents 1b2ba5c + 139133e commit 39e2bef
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 6 deletions.
37 changes: 37 additions & 0 deletions packages/ra-core/src/dataProvider/useGetList.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,43 @@ describe('useGetList', () => {
).toEqual({ id: 1, title: 'live' });
});

it('should not pre-populate getOne Query Cache if more than 100 results', async () => {
const callback: any = jest.fn();
const queryClient = new QueryClient();
const dataProvider: any = {
getList: jest.fn(() =>
Promise.resolve({
data: Array.from(Array(101).keys()).map(index => ({
id: index + 1,
title: `item ${index + 1}`,
})),
total: 101,
})
),
};
render(
<CoreAdminContext
queryClient={queryClient}
dataProvider={dataProvider}
>
<UseGetList callback={callback} />
</CoreAdminContext>
);
await waitFor(() => {
expect(callback).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.arrayContaining([
{ id: 1, title: 'item 1' },
{ id: 101, title: 'item 101' },
]),
})
);
});
expect(
queryClient.getQueryData(['posts', 'getOne', { id: '1' }])
).toBeUndefined();
});

it('should not fail when the query is disabled and the cache gets updated by another query', async () => {
const callback: any = jest.fn();
const onSuccess = jest.fn();
Expand Down
23 changes: 17 additions & 6 deletions packages/ra-core/src/dataProvider/useGetList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
import { RaRecord, GetListParams, GetListResult } from '../types';
import { useDataProvider } from './useDataProvider';

const MAX_DATA_LENGTH_TO_CACHE = 100;

/**
* Call the dataProvider.getList() method and return the resolved result
* as well as the loading state.
Expand Down Expand Up @@ -87,12 +89,21 @@ export const useGetList = <RecordType extends RaRecord = any>(
...options,
onSuccess: value => {
// optimistically populate the getOne cache
value?.data?.forEach(record => {
queryClient.setQueryData(
[resource, 'getOne', { id: String(record.id), meta }],
oldRecord => oldRecord ?? record
);
});
if (
value?.data &&
value.data.length <= MAX_DATA_LENGTH_TO_CACHE
) {
value.data.forEach(record => {
queryClient.setQueryData(
[
resource,
'getOne',
{ id: String(record.id), meta },
],
oldRecord => oldRecord ?? record
);
});
}
// execute call-time onSuccess if provided
if (options?.onSuccess) {
options.onSuccess(value);
Expand Down

0 comments on commit 39e2bef

Please sign in to comment.