DEV Community

Rohith Gilla
Rohith Gilla

Posted on

5 3

Send API response directly to a variable using hooks.

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())
  );
Enter fullscreen mode Exit fullscreen mode

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())
  );
Enter fullscreen mode Exit fullscreen mode

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay