Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
21 changes: 21 additions & 0 deletions src/useList/__tests__/useList.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,25 @@ describe('Test useList hook', () => {
await awaitTimers();
expect(result.current.loading).toBe(false);
});

it('Should support clear data before mutate', async () => {
const fetcher = jest.fn().mockResolvedValue({
total: 1,
data: [{ uuid: 1 }],
error: new Error('testError'),
});
const { result } = renderHook(() =>
useList(fetcher, { current: 1, pageSize: 20, search: '' })
);
expect(fetcher).toBeCalledTimes(1);
await waitFor(() => {
expect(result.current.data.length).toBe(1);
});
act(() => {
result.current.mutate({ search: 'test' }, { clearData: true });
});
expect(result.current.data).toStrictEqual([]);
expect(result.current.params.total).toBe(0);
expect(result.current.error).toBe(undefined);
});
});
1 change: 1 addition & 0 deletions src/useList/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ toc: content
| 参数 | 说明 | 类型 | 默认值 |
| ---------- | ---------------------- | --------- | ------ |
| revalidate | 修改后是否重新请求数据 | `boolean` | `true` |
| clearData | 请求数据前是否清除数据 | `boolean` | `true` |
10 changes: 10 additions & 0 deletions src/useList/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export interface IMutateOptions {
* 是否数据重新获取
*/
revalidate?: boolean;
/**
* 在mutate发起请求前是否清空data(包括data total error)
*/
clearData?: boolean;
}

export interface IUseListOptions {
Expand Down Expand Up @@ -49,13 +53,19 @@ export default function useList<T extends Record<string, any>, P extends Record<
const mutate = (next: Partial<P> | ((prev: P) => P) = params, options: IMutateOptions = {}) => {
const defaultOptions: IMutateOptions = {
revalidate: true,
clearData: true,
};
const nextOptions = merge(defaultOptions, options);

const tmp = typeof next === 'function' ? next(params) : { ...merge({}, params, next) };
setParams(tmp);

if (nextOptions.revalidate) {
if (nextOptions.clearData) {
setData([]);
setTotal(0);
setError(undefined);
}
performFetch(tmp);
}
};
Expand Down