use-cancelable-swr
安装
npx shadcn@latest add https://ssp-ui-registry-staging.sh3.agoralab.co/r/use-cancelable-swr.jsonyarn dlx shadcn@latest add https://ssp-ui-registry-staging.sh3.agoralab.co/r/use-cancelable-swr.jsonpnpx shadcn@latest add https://ssp-ui-registry-staging.sh3.agoralab.co/r/use-cancelable-swr.jsonbunx shadcn@latest add https://ssp-ui-registry-staging.sh3.agoralab.co/r/use-cancelable-swr.json参考
Refer to Documentation
示例
"use client"import useSWR, { type SWRConfiguration, type SWRResponse } from "swr"export const useCancelableSwr = <T>(data: { url: string key: | string | (string | Record<string, unknown>)[] | Record<string, unknown> | null},fetchOpts?: Omit<RequestInit, "signal">,swrOpts?: SWRConfiguration): [SWRResponse<T>, AbortController] => {const controller = new AbortController()return [ useSWR( data.key, () => fetch(data.url, { ...fetchOpts, signal: controller.signal, }).then((res) => res.json()), { // revalidateOnFocus: false, errorRetryCount: 3, refreshInterval: 1000 * 60, // dedupingInterval: 30000, // focusThrottleInterval: 60000, ...swrOpts, } ), controller,]}// to use it:
const [{ data }, controller] = useCancelableSWR({url: '/api', key: 'api-data'}, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
// ...
controller.abort()