Skip to content

Commit

Permalink
fix: Allow useGridDataProvider to use an inline function (#3272)
Browse files Browse the repository at this point in the history
Assumes the useGridDataProvider list function does not change so that the method can be defined inline without constantly reassigning the data provider and reloading all data
  • Loading branch information
Artur- authored Feb 23, 2025
1 parent 347b2ad commit f1dc8cb
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
9 changes: 8 additions & 1 deletion packages/ts/react-crud/src/data-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,14 @@ export type UseGridDataProviderResult<TItem> = GridDataProvider<TItem> & {
export type GridFetchCallback<TItem> = (pageable: Pageable) => Promise<TItem[]>;

export function useGridDataProvider<TItem>(list: GridFetchCallback<TItem>): UseGridDataProviderResult<TItem> {
const result = useDataProvider({ list: async (pageable) => list(pageable) });
const result = useDataProvider(
useMemo(
() => ({
list: async (pageable: Pageable) => list(pageable),
}),
[],
),
);
const dataProvider: UseGridDataProviderResult<TItem> = result.dataProvider as UseGridDataProviderResult<TItem>;
dataProvider.refresh = result.refresh;
return dataProvider;
Expand Down
15 changes: 15 additions & 0 deletions packages/ts/react-crud/test/dataprovider.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
useComboBoxDataProvider,
useDataProvider,
useGridDataProvider,
type GridFetchCallback,
type ItemCounts,
} from '../src/data-provider.js';
import type AndFilter from '../src/types/com/vaadin/hilla/crud/filter/AndFilter.js';
Expand Down Expand Up @@ -287,6 +288,20 @@ describe('@hilla/react-crud', () => {
await grid.requestPage(0);
expect(called).to.be.equal(1);
});
it('does not reassign data provider for an inline fetch function', () => {
const method1 = async (_pageable: Pageable) => await Promise.resolve([{ id: 1, name: 'Product 1' }]);
const method2 = async (_pageable: Pageable) => await Promise.resolve([{ id: 2, name: 'Product 2' }]);
type PropsType = { fetchCallback: GridFetchCallback<unknown> };

const hook = renderHook((props: PropsType) => useGridDataProvider(props.fetchCallback), {
initialProps: { fetchCallback: method1 },
});

const dataprovider1 = hook.result.current;
hook.rerender({ fetchCallback: method2 });
const dataprovider2 = hook.result.current;
expect(dataprovider1).to.be.eq(dataprovider2);
});
});

describe('useComboBoxDataProvider', () => {
Expand Down

0 comments on commit f1dc8cb

Please sign in to comment.