How can I get one response for different API pages with useSWR?

Viewed 185

I am using an API URL that has different data depend on the page URL, but I want to get all the pages URLs in one call, but not getting any data, except when I try to get only one page. Please can someone please help me out?

Here is my code:

function arrayFetcher(urlArr) {
    const fetcher = (url) => axios.get(url).then((res) => res.json());
    return Promise.all(urlArr.map(fetcher));
}
    
let urlArray = [];
for(let i = 0; i < 20; i++) {
    urlArray.push(`https://api.google.com/page=250&page=${i}&sparkline=false`);
}

const { data } = useSWR(urlArray, arrayFetcher);
    
{data && console.log(data)}
1 Answers

When passing an array as the key parameter to useSWR, each item in the array will be its own argument in the arrayFetcher function. This means that when you're trying to access urlArr inside arrayFetcher you're only accessing the first URL of the urlArray, and not the full array itself.

A possible solution is to pass an object as the key parameter in useSWR, which contains urlArray.

const fetcher = (url) => {
    return axios.get(url).then((res) => res.json());
};

const arrayFetcher = ({ urlArray }) => {
    // Get `urlArray` from object param
    return Promise.all(urlArray.map(fetcher));
};

const Component = () => {
    let urlArray = [];
    for(let i = 0; i < 20; i++) {
        urlArray.push(`https://api.google.com/page=250&page=${i}&sparkline=false`);
    }

    // Pass `urlArray` inside object as the key
    const { data } = useSWR({ urlArray }, arrayFetcher); 
    console.log(data);

    // Rest of the component
};
Related