Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
78 changes: 78 additions & 0 deletions src/useList/__tests__/useList.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,84 @@ describe('Test useList hook', () => {
expect(result.current.params).toEqual(expect.objectContaining({ search: 'test' }));
});

it('Should merge object params while replacing arrays and nullable values', () => {
type Params = {
current: number;
filters: number[];
search?: string;
nullable: string | null;
nested: {
first?: number;
second?: number;
filters?: number[];
search?: string;
};
};
const fetcher = jest.fn().mockResolvedValue({ total: 0, data: [] });
const { result } = renderHook(() =>
useList(
fetcher,
{
current: 1,
filters: [1, 2, 3],
search: 'test',
nullable: 'value',
nested: {
first: 1,
second: 2,
filters: [1, 2, 3],
search: 'nested',
},
} as Params,
{ immediate: false }
)
);

act(() => {
result.current.mutate(
{
filters: [4, 5],
search: undefined,
nullable: null,
nested: { first: 3, filters: [4, 5], search: undefined },
},
{ revalidate: false }
);
});

expect(result.current.params).toEqual({
current: 1,
filters: [4, 5],
search: undefined,
nullable: null,
nested: {
first: 3,
second: 2,
filters: [4, 5],
search: undefined,
},
total: 0,
});
});

it('Should preserve circular references when merging object params', () => {
const fetcher = jest.fn().mockResolvedValue({ total: 0, data: [] });
const previous: Record<string, any> = { value: 'previous' };
const next: Record<string, any> = { value: 'next' };
previous.self = previous;
next.self = next;
const { result } = renderHook(() =>
useList(fetcher, { nested: previous }, { immediate: false })
);

act(() => {
result.current.mutate({ nested: next }, { revalidate: false });
});

expect(result.current.params.nested.value).toBe('next');
expect(result.current.params.nested.self).toBe(result.current.params.nested);
});

it('Should support get data with current params', () => {
const fetcher = jest.fn().mockResolvedValue({
total: 1,
Expand Down
4 changes: 1 addition & 3 deletions src/useList/demos/mutate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ export default () => {
const handleReset = async () => {
form.resetFields();
const values = await form.validateFields();
// 当传入值有 undefined 的时候,采用 functional 的写法。
// 因为底层使用的 lodash 的 merge,采用赋值写法不会对 undefined 做合并
mutate((pre) => ({ ...pre, ...values }));
mutate({ ...values });
};

return (
Expand Down
4 changes: 1 addition & 3 deletions src/useList/demos/mutateOptions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ export default () => {
const handleReset = async () => {
form.resetFields();
const values = await form.validateFields();
// 当传入值有 undefined 的时候,采用 functional 的写法。
// 因为底层使用的 lodash 的 merge,采用赋值写法不会对 undefined 做合并
mutate((pre) => ({ ...pre, ...values }), { revalidate, clearData });
mutate({ ...values }, { revalidate, clearData });
};
const [revalidate, setRevalidate] = useState(true);
const [clearData, setClearData] = useState(true);
Expand Down
2 changes: 1 addition & 1 deletion src/useList/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ toc: content
<code src="./demos/basic.tsx" title="基础使用"></code>
<code src="./demos/sort.tsx" title="筛选和过滤"></code>
<code src="./demos/options.tsx" title="相关配置" description="设置 immediate 值防止初始化的时候进行请求"></code>
<code src="./demos/mutate.tsx" title="相关配置" description="用 undefined 覆盖 prevPrams 时,需采用 functional 的写法 "></code>
<code src="./demos/mutate.tsx" title="参数修改" description="普通对象递归合并,数组、undefined 和 null 会完整覆盖旧值"></code>
<code src="./demos/mutateOptions" title="mutate相关配置" description="revalidate 修改后请求数据,clearData 请求前清除数据"></code>
<code src="./demos/query" title="搜索" description="支持修改后重置搜索"></code>

Expand Down
27 changes: 25 additions & 2 deletions src/useList/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { merge } from 'lodash-es';
import { isPlainObject, merge } from 'lodash-es';

const mergeParams = (
previous: Record<string, any>,
next: Record<string, any>,
merged = new WeakMap<object, Record<string, any>>()
): Record<string, any> => {
const cached = merged.get(next);
if (cached) return cached;

const result = { ...previous };
merged.set(next, result);

Object.keys(next).forEach((key) => {
const previousValue = previous[key];
const nextValue = next[key];
result[key] =
isPlainObject(previousValue) && isPlainObject(nextValue)
? mergeParams(previousValue, nextValue, merged)
: nextValue;
});

return result;
};
Comment thread
LuckyFBB marked this conversation as resolved.

export type Fetcher<T, P> = (params: P) => Promise<{ data: T[]; total: number }>;

Expand Down Expand Up @@ -91,7 +114,7 @@ export default function useList<T extends Record<string, any>, P extends Record<
};
const nextOptions = merge(defaultOptions, options);

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

if (nextOptions.revalidate) {
Expand Down
Loading