Skip to content

Commit

Permalink
Merge pull request #6188 from marmelab/fix-usegetmany-enabled
Browse files Browse the repository at this point in the history
Fix useGetMany Does Not Respect Enabled Option
  • Loading branch information
fzaninotto authored Apr 19, 2021
2 parents ff6b318 + b4157a5 commit a631a6d
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
38 changes: 38 additions & 0 deletions packages/ra-core/src/dataProvider/useGetMany.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,44 @@ describe('useGetMany', () => {
]);
});

it('should not call the dataProvider with a GET_MANY on mount if enabled is false', async () => {
const dataProvider = {
getMany: jest.fn(() =>
Promise.resolve({ data: [{ id: 1, title: 'foo' }] })
),
};
const { dispatch, rerender } = renderWithRedux(
<DataProviderContext.Provider value={dataProvider}>
<UseGetMany
resource="posts"
ids={[1]}
options={{ enabled: false }}
/>
</DataProviderContext.Provider>
);
await new Promise(resolve => setTimeout(resolve));
expect(dispatch).toBeCalledTimes(0);
expect(dataProvider.getMany).toBeCalledTimes(0);

rerender(
<DataProviderContext.Provider value={dataProvider}>
<UseGetMany
resource="posts"
ids={[1]}
options={{ enabled: true }}
/>
</DataProviderContext.Provider>
);
await new Promise(resolve => setTimeout(resolve));
expect(dispatch).toBeCalledTimes(5);
expect(dispatch.mock.calls[0][0].type).toBe('RA/CRUD_GET_MANY');
expect(dataProvider.getMany).toBeCalledTimes(1);
expect(dataProvider.getMany.mock.calls[0]).toEqual([
'posts',
{ ids: [1] },
]);
});

it('should aggregate multiple queries into a single call', async () => {
const dataProvider = {
getMany: jest.fn(() =>
Expand Down
6 changes: 5 additions & 1 deletion packages/ra-core/src/dataProvider/useGetMany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const DataProviderOptions = { action: CRUD_GET_MANY };
const useGetMany = (
resource: string,
ids: Identifier[],
options: UseGetManyOptions = {}
options: UseGetManyOptions = { enabled: true }
): UseGetManyResult => {
// we can't use useQueryWithStore here because we're aggregating queries first
// therefore part of the useQueryWithStore logic will have to be repeated below
Expand All @@ -116,6 +116,10 @@ const useGetMany = (
}
dataProvider = useDataProvider(); // not the best way to pass the dataProvider to a function outside the hook, but I couldn't find a better one
useEffect(() => {
if (options.enabled === false) {
return;
}

if (!queriesToCall[resource]) {
queriesToCall[resource] = [];
}
Expand Down

0 comments on commit a631a6d

Please sign in to comment.