Home > database >  NextJS SWR multiple API calls returnin undefined
NextJS SWR multiple API calls returnin undefined

Time:11-03

So when I try to fetch data from API endpoints with SWR library I'm able to only get the first fetcher function to return data... All API endpoints are working fine if I check them in browser but in code data1,2,3,4 all return undefined if I console log them, am I not using this library correctly to fetch multiple APIs?

 const fetcher = async () => {
          const response = await fetch("API");
          const data = await response.json();
          return data;
        };
        
        const fetcher1 = async () => {
          const response1 = await fetch("API");
          const data1 = await response1.json();
          return data1;
        };
        
        const fetcher2 = async () => {
          const response2 = await fetch("API");
          const data2 = await response2.json();
          return data2;
        };
        
        const fetcher3 = async () => {
          const response3 = await fetch("API");
          const data3 = await response3.json();
          return data3;
        };
        
        const fetcher4 = async () => {
          const response4 = await fetch("API");
          const data4 = await response4.json();
          return data4;
        };
        
        export default function Dashboard(props) {
          const {data, error} = useSWR("name1", fetcher);
          const {data1, error1} = useSWR("name2", fetcher1);
          const {data2, error2} = useSWR("name3", fetcher2);
          const {data3, error3} = useSWR("name4", fetcher3);
          const {data4, error4} = useSWR("name5", fetcher4);
        
          if (error) return "Error";
          if (!data) return "Loading";
        
          console.log(data);
          return (
               <div>{data.name}</div>
          )

CodePudding user response:

Note that useSWR always return data as data, not data1 or data2.

You are destructing object in a wrong way. In fact it should be done like

const { data: data1, error: error1 } = useSWR('name2', fetcher1)
  • Related