In my last post, it wrote about the topic of data fetching and caching on the server side. Today I want to introduce a module that handles this on the client side, i.e., in the browser.

SWR module

SWR is a module that particularly simplifies asynchronous data fetch operations in React, using hooks, significantly.

In the description on npm they write: "The name SWR is derived from stale-while-revalidate, a cache invalidation strategy popularized by HTTP RFC 5861. SWR first returns the data from cache (stale), then sends the request (revalidate), and finally comes with the up-to-date data again."

And this is done by a simple hook as the following example shows:

Create project

Run

npx create-react-app my-app --template typescript

in your terminal to start a Single Page Application in TypeScript.

Switch to my-app subfolder and then open src/App.tsx file and replace its content with this test code:

import axios from 'axios';
import React, { useCallback } from 'react';
import useSWR from "swr";

import './App.css';

interface IRandomUserList {
  results: {
    gender: string;
    name: {
      first: string;
      last: string;
    },
  }[];
}

function App() {
  // define a "key" with the first argument for useSWR(), which is
  // nothing else as the first argument for the function,
  // which is subitted as second argument to useSWR()
  //
  // this "fetcher function" is responsible for fetching the data, which
  // it has to be provide as return value
  //
  // if an error is thrown in this function, the error object
  // will be stored in `error` 
  const {
    data, error, isLoading, mutate
  } = useSWR('https://randomuser.me/api/?results=10', async (url) => {
    const response = await axios.get<IRandomUserList>(url);

    return response.data;
  });

  const renderContent = useCallback(() => {
    if (isLoading) {
      return <div>Loading data ...</div>;
    }

    if (error) {
      return <div>Could not load data: {String(error)}</div>;
    }

    return (
      <>
        <ul>
          {data?.results.map((randomUser) => {
            const {
              gender,
              name
            } = randomUser;

            return (
              <li>{name.last}, {name.first} ({gender})</li>
            );
          })}
        </ul>

        {/* mutate() will reload/refresh the data */}
        <button onClick={() => mutate()}>Refresh</button>
      </>
    );
  }, [data?.results, error, isLoading, mutate]);

  return renderContent();
}

export default App;

Install dependencies

Before we can start the project, we have to install the following dependencies:

npm install swr axios --save

Run the project

Run

npm start

in your terminal.

Some seconds later you should be able to open http://localhost:3000/ in your browser.

Conclusion

That’s all! 😎

Have fun while trying it out! 🎉