Pagination example fails in CRA with "'useSWR' cannot be called inside a callback" error
See original GitHub issueI’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
- swr@0.1.10
- react@16.12.0
- react-scripts@3.2.0
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:6 (3 by maintainers)
Top Results From Across the Web
React Hook cannot be called inside a callback - Stack Overflow
As the error tells, you should move your custom hook useQuery out of useEffect. You can add it on top of your component...
Read more >SWR: React Hooks for Data Fetching
SWR is a React Hooks library for data fetching. SWR first returns the data from cache (stale), then sends the fetch request (revalidate),...
Read more >A Look At React Hooks: useSWR for Data Fetching in React
Let's look at SWR and useSWR, and learn how it can enable our React apps to fetch, cache and work with data more...
Read more >Invalid hook call. Hooks can only be called inside the body of ...
The error "Invalid hook call. Hooks can only be called inside the body of a function component" occurs for multiple reasons, having a...
Read more >callback keyword in javascript Code Example - Code Grepper
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@quietshu thank you for the quick response!
I had to move the eslint comment but confirming this works for now:
Is there a plan to fix this? To temporarily avoid the error, I rename useSWR to swr.
It’s tricky.