(
fetcher: Fetcher<T, P>,
initialParams: P | (() => P),
rawOptions: IUseListOptions = { immediate: true }
)
| 56 | } |
| 57 | |
| 58 | export 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 | }; |
no test coverage detected