loading...

Send API response directly to a variable using hooks.

gillarohith profile image Rohith Gilla ・2 min read

We will be cruising through the following topics

  • What the heck is SWR?
  • Usage of SWR
  • What if there are multiple endpoints?

What the heck is SWR

This is an awesome library for remote data fetching.
The name “SWR” is derived from stale-while-revalidate, an HTTP cache invalidation strategy popularized by RFC 5861.

SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.

You can read more about SWR here.

Usage of SWR

To demonstrate the usage, I will be taking an example which involves the use of the following API

For instance, let's assume we want to load https://covid19.mathdro.id/api/ into a variable.
Usually, we use axios library inside useEffect hook and store the data using a state created by useState hook.

But now, SWR simplifies all your hard work into one command.

const { data,error } = useSWR(
    "https://covid19.mathdro.id/api/",
    url => fetch(url).then(_ => _.json())
  );

Now the data variable contains the response fetched from the API endpoint. The console.log(data) looks like this.

Code example

Wow, sounds perfect right 🙌🏻

What if there are multiple endpoints?

Now you may be wondering 🤔 what if there are multiple endpoints you need to get data from, how to name the variables data and error.

We can name them in the way shown in the below snippet to overcome this problem.

const { data: generalDetails, error: generalDetailsError} = useSWR(
    "https://covid19.mathdro.id/api/",
    url => fetch(url).then(_ => _.json())
  );

const {data: dailyData, error:dailyDataError} = useSWR(
        "https://covid19.mathdro.id/api/daily",
        url => fetch(url).then(_ => _.json())
    );

const {
    data: covidCases,
    error: covidCasesError,
  } = useSWR("https://covid19.mathdro.id/api/confirmed", (url) =>
    fetch(url).then((_) => _.json())
  );

Now you can use them as different variables.
I am not inserting the images of the log statements in the console, because these responses are enormous.

Hope you enjoyed the article.
Peace ✌🏻,
Rohith Gilla

Discussion

pic
Editor guide