Skip to content

cstrnt

Data Fetching in React with SWR

React, Data-Fetching2 min read

We will now now have a look at SWR by Vercel (formerly zeit). It calls itself React Hooks for Remote Data Fetching which pretty much describes it's purpose. SWR makes use of a concept called stale-while-revalidate which allows the UI to feel more reactive as every time you call your remote API the hook will return the cached values first while waiting for the response from the server. As soon as it got the data from the server it will revalidate the cache and returns the freshest data to the UI. This comes in really handy when you change pages (e.g. using react-router) as the data will be loaded from the cache first. This makes it possible to not show loading spinners every time you change to a page you already visited. But let's get into examples:

Basic Usage

Lets break this code into smaller chunks again:

Right here we're defining the unique key for that particular query. In our case this is the endpoint of the API we are calling. To use SWR properly you should always use the same key for the same request, because SWR uses the key to cache the data. The second argument fetcher is some kind of function which creates a HTTP-Request. In our case it is just window.fetch. But you can also use something such as axios. the useSWR hook then passes the key as the first argument to that fetcher function. Therefore I would recommend adding the base URL to the API your going to call to the fetch function like this:

The next pieces are { data, error} which are returned from the hook. Those ones are quite easy as they speak for themselves. data is the actual data returned from the server. It also can be undefined when the data is still loading. This happens only on the first load because there won't be any loading when getting the data from the cache. error will undefined if everything is going well, but if there was some kind of error during the fetch call this object will hold the error.

The next step is to give the user feedback what is happening right now. We do this by returning JSX Elements depending on the two variables we got from our hook. First of all we are going to check if there was an error. If so we display an error message or redirect the user. After that we check whether data has some values in it. If not, we know that our application is loading (because there is no error) and we can show the user a loading indicator (e.g. a spinner).

And that's it. Pretty clean, huh?

© 2020 by cstrnt. All rights reserved.