reactjsnext.jsswr

Calling multiple endpoints using NextJS and the SWR library


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.


Solution

  • 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 (userError) return <div>Failed to load users</div>;
    if (ballonError) return <div>Failed to load ballons</div>;