Search code examples
javascripttypescriptnext.jsswr

SWR size, setSize do not exist on type SWRResponse<any, any>?


I've been testing Vercel's SWR lately, it looks like the best lib for Next.js data fetching. I have some trouble making it work with TypeScript though.

As in docs I'm trying to build a infinite loader using this code:

const { data, error, isValidating, mutate, size, setSize } = useSWRInfinite(
  getKey, fetcher?, options?
)

But I'm getting those errors:

Property 'size' does not exist on type 'SWRResponse<any, any>'.ts(2339)
Property 'setSize' does not exist on type 'SWRResponse<any, any>'.ts(2339)

The rest of the arguments seem to be there, only the last two aren't. What am I missing here? It works perfectly fine without TypeScript. I have both latest versions of Next and SWR. I've tried following the tutorial and adding getKey function, but without luck, the error always occurs.

Any hints?


Solution

  • The fact that TypeScript identifies the return type as SWRResponse indicates that you're probably importing the default export (useSWR hook) of swr rather than useSWRInfinite hook.

    import useSWR from 'swr'
    

    Make sure to import useSWRInfinite from its named export.

    import { useSWRInfinite } from 'swr'
    

    From version 1.x, the syntax to import useSWRInfinite changed slightly. You should now use:

    import useSWRInfinite from 'swr/infinite'