MCPcopy Create free account
hub / github.com/DTStack/dt-react-component / useList

Function useList

src/useList/index.ts:58–124  ·  view source on GitHub ↗
(
    fetcher: Fetcher<T, P>,
    initialParams: P | (() => P),
    rawOptions: IUseListOptions = { immediate: true }
)

Source from the content-addressed store, hash-verified

56}
57
58export default function useList<T extends Record<string, any>, P extends Record<string, any>>(
59 fetcher: Fetcher<T, P>,
60 initialParams: P | (() => P),
61 rawOptions: IUseListOptions = { immediate: true }
62): UseListResponseState<T, P> {
63 const [error, setError] = useState<Error | undefined>(undefined);
64 const [data, setData] = useState<T[]>([]);
65 const [total, setTotal] = useState(0);
66 const [params, setParams] = useState<P>(initialParams);
67 const [loading, setLoading] = useState(false);
68 const lastRequestId = useRef<symbol | undefined>(undefined);
69
70 const options = useMemo(() => merge({ immediate: true }, rawOptions), [rawOptions]);
71
72 const performFetch = (raw = params) => {
73 const requestId = Symbol('id');
74 lastRequestId.current = requestId;
75 setLoading(true);
76 fetcher(raw)
77 .then(({ data, total }) => {
78 setData(data);
79 setTotal(total);
80 })
81 .catch(setError)
82 .finally(() => {
83 lastRequestId.current === requestId && setLoading(false);
84 });
85 };
86
87 const mutate = (next: Partial<P> | ((prev: P) => P) = params, options: IMutateOptions = {}) => {
88 const defaultOptions: IMutateOptions = {
89 revalidate: true,
90 clearData: true,
91 };
92 const nextOptions = merge(defaultOptions, options);
93
94 const tmp = typeof next === 'function' ? next(params) : { ...merge({}, params, next) };
95 setParams(tmp);
96
97 if (nextOptions.revalidate) {
98 if (nextOptions.clearData) {
99 clearData();
100 }
101 performFetch(tmp);
102 }
103 };
104
105 const clearData = () => {
106 setData([]);
107 setTotal(0);
108 setError(undefined);
109 };
110
111 const clear = () => {
112 clearData();
113 setParams(initialParams);
114 setLoading(false);
115 };

Callers 7

basic.tsxFile · 0.85
mutateOptions.tsxFile · 0.85
query.tsxFile · 0.85
options.tsxFile · 0.85
mutate.tsxFile · 0.85
sort.tsxFile · 0.85
useList.test.tsFile · 0.85

Calls 1

performFetchFunction · 0.85

Tested by

no test coverage detected