Use SWR to fetch multiple times to populate an array

Viewed 2318

I have a component in React in need of an array of users. I'm able to fetch one single user at a time with useUwr like so:

export function Hello(id: number) {
  const { data } = useSWR('/api/user/{id}', fetcher)

  return <div>hello {data.name}!</div>
}

What I need now is an array of users, so basically:

var users = [];  
for(var i = 0; i < 100; i++) {
   const { data } = useSWR('/api/user/{i}', fetcher); 
   users.push(data);
}

Issue with this approach is Error: Rendered more hooks than during the previous render.

Was thinking that there must be a smarter way to fetch the data of 100 users. Thanks for any suggestion.

3 Answers

Try this:

function arrayFetcher(...urlArr) {
  const f = (u) => fetch(u).then((r) => r.json());
  return Promise.all(urlArr.map(f));
}

export function Hello(id: number) {
  let urlArray = [];
  for(let i = 0; i < 100; i++) {
    urlArray.push(`/api/user/${i}`);
  }
  const { data } = useSWR(urlArray, arrayFetcher);

  return (
    <ul>{data && data.map(x => <li key={x.name}>x.name</li>)}</ul>
  )
}
function multiFetcher(...urls) {
  return Promise.all(urls.map(url => fetcher(url))
}

const { data: [data1, data2, data3] } = useSWR([url1, url2, url3], multiFetcher)

add urlArray in array

const { data } = useSWR([urlArray], arrayFetcher);
Related