Data Fetching: FETCH API Approach vs SWR Approach
What is one of the essential things for the application? Yes, data. Unfortunately, applications that do not contain data cannot go beyond being a promotional page.
Although the article starts as if it is about the back end, I will talk about the “Data Fetching with JavaScript” topic that we use to reach the data we show to the end-user on the front end.
We will be evaluating 2 different data retrieval methods to access and use data. The first of these will be the FETCH API and the other will be the SWR (Stale While Revalidate) methods. I will also talk about the positive effects that we can leave on the user with the SWR method.
In addition, since we will need a database for practical examples, I created a fake database consisting of users and their orders. I will explain the examples through this application. (You can access the application’s codes from the GitHub repository, which I will specify at the end of the article.)
Data Fetching
Data Fetching, in its simplest definition, is the acquisition of data to be displayed on the front end by communicating with the back end. We can perform this communication through methods such as the Fetch API.
What is the FETCH API?
Fetch API is a method of receiving and sending data provided to us by JavaScript. This method has an asynchronous nature. Technically, Fetch API is a method provided to us ready to use within the window object and returns a Promise structure. Thanks to the Promise structure, we encounter a resolved or rejected response. You can find more detailed information about the Promise structure on MDN.
How does FETCH API work?
We can consider the working principle of Fetch API in 3 stages. These are, in order;
- On the user side (in the browser), a request is sent to the server
- The server fulfills the request
- In the last stage, there are 2 possibilities. If the request is successful, the data we promised to see returns to us from the server as a response. If the request fails, we get an HTTP error code.
We can visually observe these steps in the diagram below.
What is the cost of the FETCH API method?
In the requests we manage with this method, even if we have accessed the data before in our application, it must be accessed again in the UI each time. It is normal to see this in methods written in pure JavaScript, in which the application is reloaded each time per page when switching between pages.
However, in the Single Page Application method, which is widely used today, there is usually no need to load a web page from scratch. It is sufficient to update the component containing the change. Libraries like React handle this quite successfully. For this reason, there is no need to refresh the entire page. For more information about SPA, you can check MDN’s reference page.
FETCH API: An example in terms of code, UI, and UX
Below you can see a code sample written with the Fetch API. (I would also like to draw your attention to how long the syntax is)
fetch('http://localhost:5001/users')
.then((response) => response.json())
.then((data) => console.log(data));
As I said we needed a database. I’ve added a 2-seconds delay to the fake database response that I prepared, and let’s see how it looks on the UI.
In the way that can be seen from the recording time in the lower left, I tried to reach the same data 3 times within 13 seconds.
As seen in the gif, the data is reset each time and the request is thrown. We see the loading spinner in the UI. However, after the first request, we already had data.
What is SWR (Stale While Revalidate)?
First of all, SWR is a data capture model. It is not a method that can be used alone as a substitute for FETCH API. Since SWR also needs a fetcher to receive the data, we will use the Fetch API.
As the name suggests, it has a working principle of using stale data during revalidation. In other words, when we send a request to a server for the first time, everything proceeds just like in the FETCH API. We wait for the response from the server and the loading component appears at this time. Then we either access the data or get an error.
In the scenario where we reach the data successfully, the real magic and the part that is different from the Fetch API start here. Since we have the already existing cached data from the first request, we can show this data directly on the UI. Think about how important it is in terms of user experience, please. You never come to the same page empty-handed.
I seem to hear this question here, but what if the data has changed? While SWR shows you the stale data, it also sends a request to the server again. In this way, if there is changed data, these are also going to be reflected in the UI.
How does SWR (Stale — While — Revalidate) work?
We can consider the working principle of SWR in 5 steps. These are, in order;
- A request is sent to the server ( initial request)
- Locally cached data is presented to us. (we already have it after the initial request)
- There may have been changes in the data we want to reach. To understand this, a request is sent to the server
- The server returns us up-to-date data
- Finally, we reach out to the current data in the browser by the user. (Also, this is our new stale data )
Let’s observe the working logic of SWR with 2 diagrams.
Diagram 1: The working flow of SWR
Diagram 2: The working flow of SWR
So far, we’ve talked about SWR’s cache strategy and general information about how it works. We also proceeded by visualizing this with a diagram. As the next step, I will talk about how to use the SWR library that Vercel has developed for React.
SWR (Stale — While — Revalidate): An example in terms of code, UI, and UX
Below we can see an example of code written in SWR. (I would like to draw your attention to the simplicity of Syntax)
First, we need a fetcher function and this is where the FETCH API comes into play.
NOTE: We can define baseUrl and fetcher in SWRConfig by wrapping the App, so we can use the useSWR Hook in a simpler way. Detailed configuration information can be found in the documentation.
const baseUrl = 'http://localhost:5001';
const fetcher = (baseUrl: string) => fetch(baseUrl).then((r) => r.json());
In _app.tsx,
import { SWRConfig } from 'swr';
import type { AppProps } from 'next/app';
import '../styles/globals.scss';
const baseUrl = 'http://localhost:5001';
export default function App({ Component, pageProps }: AppProps) {
const fetcher = (baseUrl: string) => fetch(baseUrl).then((r) => r.json());
return (
<SWRConfig
value={{
fetcher: (url: string) => fetcher(`${baseUrl}${url}`),
}}
>
<Component {...pageProps} />
</SWRConfig>
);
}
Now, what we need next is a one-line request.
const { data } = useSWR<IUser[]>(`/users`);
Let’s skip to an example. There is also a 2-second delay in the database response. As can be seen in the gif below, I am sending 3 requests again and I ask you to pay attention to the ones after the first request. The data will appear directly on the UI without seeing the loading spinner.
See how many times I’ve visited the page! After the first request, it’s like I’m navigating through files on my own computer. How wonderful isn’t it!
What are the benefits of using stale data?
Thanks to stale data, we can achieve very good results in terms of UX, as seen in the gif. Users can interact with your app much more. Besides, who wants to wait every time to see something they already know?
In addition, it is an important structure for Optimistic UI, which is a very popular front-end development method.
Comparison of FETCH API and SWR methods on the basis of UI
My aim under this title is to make the comparison of Fetch API and SWR topics, which I have discussed separately, more visually understandable. For this reason, I will share a gif that we sent 2 requests side by side on a single screen. I’m sure this image will give a clear answer to many questions that may be on your mind.
Since the gif proceeds in a loop, I would like to draw your attention to the existence of the recording time in the lower left. As you will notice, after we reach the data once with SWR, we do not expose the user to the loader spinner again because we have stale data.
To summarize, as seen in the comparison gif, both methods give the same result in the first request. However, on the second visit, the data appears directly on our user interface without seeing any loader screen, as SWR presents stale data to us.
Thank you for taking the time to read my article! Your thoughts and comments are invaluable. If so, Arrivederci!
Türkçe: buradan erişebilirsiniz
Additional Part
If you say that the gifs were not enough, you can also access the video that I wandered in the application for a longer time period here. Youtube: https://youtu.be/MJeofIcEWLo
GitHub link of the project to access the codes: https://github.com/ooguzyuksel/data-fetching-fetch-vs-swr
You can reach me through the channels below,
LinkedIn: https://www.linkedin.com/in/developeroguzyuksel/
GitHub: https://github.com/ooguzyuksel
Oğuzhan YÜKSEL
Frontend Developer ÇSTech
References and Sources:
- https://juejin.cn/post/7005497283399647268
- https://swr.vercel.app/docs/global-configuration
- https://developer.mozilla.org/en-US/docs/Glossary/SPA
- https://www.toptal.com/react-hooks/stale-while-revalidate
- https://blog.zingsoft.com/how-to-make-a-chart-using-fetch-rest-apis/
- https://www.vuemastery.com/blog/data-fetching-and-caching-with-swr-and-vuejs/
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise