File size: 824 Bytes
87337b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"use client"

import { type SWRResponse, type SWRConfiguration } from "swr"
import useSWR from "swr"

// https://github.com/vercel/swr/discussions/2330#discussioncomment-4460054
export function useCancelableSWR<T>(
  key: string,
  opts?: SWRConfiguration,
): [SWRResponse<T>, AbortController] {
  const controller = new AbortController()
  return [
    useSWR(
      key,
      (url: string) =>
        fetch(url, { signal: controller.signal }).then((res) => res.json()),
      {
        // revalidateOnFocus: false,
        errorRetryCount: 3,
        refreshInterval: 1000 * 60,
        // dedupingInterval: 30000,
        // focusThrottleInterval: 60000,
        ...opts,
      },
    ),
    controller,
  ]
  // to use it:
  // const [{ data }, controller] = useCancelableSWR('/api')
  // ...
  // controller.abort()
}