How can I iterate over the list of URLs and make a call to the server using useSWR hook

Viewed 305

I am working on a ReactJS Web application and got stuck in a problem. Problem is I have an array of URLs of some JSON data and I want to fetch all these JSON data from server using "useSWR" hook (so that the fetched data gets cached as well). Now the problem is as per the rules we cannot use hooks inside any loop or block.

Example -

  1. What I have - ["http://someapi/a.json", "http://someapi/b.json", "http://someapi/c.json"]
  2. What I want to do - iterate over this array and call these urls using useSWR hook, so that I have a list of [ JSON ObjectA, JSON ObjectB, JSON ObjectC ]
  3. Why I am trying to use "useSWR" because I know, this data will not gonna change for 24Hours and I want to cache these values.

Can anyone suggest me how can I iterate over the list of URLs and make a call to the server using useSWR hook? And is there's some other optimized approach to solve this problem? Any help or guidance is highly appreciated.

1 Answers

One of the option i think is to create React FetchComponent with url prop and use the useSWR hook inside. Render components as number of urls. Something like this:

["http://someapi/a.json", "http://someapi/b.json", "http://someapi/c.json"].map(url=><FetchComponent url={url}/>)
Related