Swr: Pagination example fails in CRA with "'useSWR' cannot be called inside a callback" error

Created on 19 Nov 2019  路  6Comments  路  Source: vercel/swr

I'm having trouble using (either) pagination example in a Create React App project. As far as I can see my code tracks with the examples, reduced some here:

import useSWR, { useSWRPages } from 'swr';

function List({ query }) {
  const {
    pages,
    isLoadingMore,
    isReachingEnd,
    loadMore
  } = useSWRPages(
    'example',

    ({ offset, withSWR }) => {
      const { data: resource, error } = withSWR(
        useSWR('/data')
      );

      if (!resource) return null;
      if (error) throw new Error(error);

      return resource.data.map(item => (
        <Item key={item.id} {...item} />
      ));
    },

    (SWR, index) => {
      return 1;
    },

    []
  );

  return pages;
}
...

Running this I get an error overlay:

./src/app/example.js
 Line 71:9:   React Hook "useSWR" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function  react-hooks/rules-of-hooks

pagination

Most helpful comment

@quietshu thank you for the quick response!

I had to move the eslint comment but confirming this works for now:

const { data: resource, error } = withSWR(
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useSWR('/data')
);

All 6 comments

Currently we don't have a good way to avoid that, maybe you can disable eslint for that specific line as a temporary fix:

      // eslint-disable-next-line react-hooks/rules-of-hooks
      const { data: resource, error } = withSWR(
        useSWR('/data')
      );

Maybe have withSWR use the first arg as a callback @quietshu ?

const {data, error} = withSWR((useSWR) => 
    useSWR('/data');
);

@quietshu thank you for the quick response!

I had to move the eslint comment but confirming this works for now:

const { data: resource, error } = withSWR(
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useSWR('/data')
);

I have this problem :(

Is there a plan to fix this?
To temporarily avoid the error, I rename useSWR to swr.

import swr, {useSWRPages} from 'swr';

It's tricky.

The new pagination API has launched: https://swr.vercel.app/docs/pagination. Feel free to reopen if you are still encountering an issue!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dandrei picture dandrei  路  3Comments

loveholly picture loveholly  路  3Comments

baoduy picture baoduy  路  4Comments

polc picture polc  路  3Comments

zahraHaghi picture zahraHaghi  路  3Comments