I have a NextJS project where I'm trying to use SWR to fetch data. My problem is:
when I use more than two useSWR
-hooks in one component I get these hook errors:
Warning: React has detected a change in the order of Hooks called by ComponentExample. This will lead to bugs and errors if not fixed.
Uncaught Error: Update hook called on initial render. This is likely a bug in React. Please file an issue.
Here is a minimum reproduction code repository: https://github.com/LarsFlieger/swr-suspense-multiple
In Component.tsx
I'm trying to do 3 fetches and console logging the output:
"use client";
import useSWR from "swr";
const fetchWithDelay = async (url: string) => {
const delay = parseInt(url) * 1000;
await new Promise((resolve) => setTimeout(() => resolve(url), delay));
return url;
};
export const ComponentExample: React.FC = () => {
const { data: dataAfter1 } = useSWR("1", fetchWithDelay, {
suspense: true,
});
console.log(dataAfter1);
const { data: dataAfter2 } = useSWR("2", fetchWithDelay, {
suspense: true,
});
console.log(dataAfter2);
const { data: dataAfter3 } = useSWR("3", fetchWithDelay, {
suspense: true,
});
console.log(dataAfter3);
return (
<main>
<p>Page loaded!</p>
</main>
);
};
How can I fix this issue? I can not find any general rule if it's okay to use multiple hooks but as far as I understand it should be okay since:
- in several examples there multiple: https://swr.vercel.app/docs/conditional-fetching#dependent