4

I am using the SWR library in my NextJS project and currently i am building out a dashboard. I want to hit multiple endpoints to get different data, but I can't find any reference of making multiple calls to endpoints using SWR.

The syntax i am using is as follows;

const { data, error } = useSWR('/api/users', fetcher);
if (error) return <div>Failed to load</div>

const { data, error } = useSWR('/api/balloons', fetcher);
if (error) return <div>Failed to load</div>

If i use the above code, it errors out saying that data has already been defined, but if i change data to something unique in each try, it doesn't work at all.

4

2 回答 2

4

You can rename the destructured values.

Try the following:

const { data: users, error: userError } = useSWR("/api/users", userFetcher);
const { data: baloons, error: ballonError } = useSWR("/api/balloons", balloonsFetcher);

if (error) return <div>Failed to load</div>;
if (error) return <div>Failed to load</div>;
于 2021-03-17T17:03:41.667 回答
1

you can have nested hooks.

This is an example more complex that nested hooks, in this one I adding some security to avoid fetch if the user doesnt have permission:

Imagine we are creating a banking application. In order for our users to deposit funds, they must first verify their account for compliance and regulatory purposes. Therefore, we know that any user who has not yet verified their account, cannot have balances.

As you can see in our custom hook, we use our useUserSettings SWR hook to fetch the user settings. If we have not yet fetched the settings, then we return null from our key function and abort our fetch. Once we have fetched the settings, we check if the user is verified. If the user is verified, then we make a call to our balances endpoint. If not, we turn an empty array, as we know the user cannot have balances.

function useProjects() {
  const { data: user } = useUserSettings();
  return useSWR(() => {
    if (user.id) {
      return `/api/projects?user=${user.id}`;
    }
    return null;
  }, fetcher);
}
于 2021-08-18T20:33:32.280 回答