SWR (sample)

Welcome to my third blog for this whole year.. yeahh!

March 13, 20231052 words

Table of Contents

SWR is a great package from Zeit to help make it easier to fetch remote data with hooks. It is based on the stale-while-revalidate RFC, which in simple terms says to show stale (old) data while you are fetching a new version of the data. The idea is that it is better to show something old if you have it rather than a blank screen.

We will show how to use SWR, how to configure it globally, and a pattern I like to use which separates data fetching from data display.

Code is available at: https://github.com/leighhalliday/crime-mapping

An SWR Fetcher

The useSWR hook requires two things to make it work:

useSWR("/crimes/passion", fetcher);
<article className="prose">
  <p>Hello world</p>
</article>

The fetcher we'll be working with receives the incoming arguments (in our case the URL), passes them on to fetch, and then resolves the response to produce JSON.

const fetcher = (...args) => fetch(...args).then((res) => res.json());

Global Config Provider

Rather than having to pass the fetcher function, and any other config options you may want to set on every call to the useSWR hook, you can wrap your components with a provider called SWRConfig. This allows you to globally set config options to be used with every useSWR hook call. In our example we'll pass the fetcher function to it so it can be used globally.

export default function App() {
  return (
    <SWRConfig value={{ fetcher }}>
      <Crimes />
    </SWRConfig>
  );
}

Separating Data From Display

When working with data, be it GraphQL or data from a REST API, I like to separate out data fetching logic from display logic. We'll be doing the same here in this example, and the psuedo-code/logic looks like:

function Crimes() {
  // fetch data
  // handle errors
  // handle loading state
  // render display component
}
 
function DisplayCrimes({ crimes }) {
  // only have to deal with displaying data
}

Separating data from display also allows you to test visual changes in isolation, useful for testing or showing how the component would look like in Storybook without having to mock all of your API calls.

Fetching Data

Because we are using SWRConfig to configure our useSWR hook calls globally, we don't have to worry about passing the fetcher function to this hook, we only have to worry about passing our "key" (URL to fetch the data). As a response we get an object that we can extract {data, error} from.

After dealing with error states and lack of data (loading state), we are now ready to pass the data onto our DisplayCrimes component whose job is to simply render the fetched data.

function Crimes() {
  const url =
    "https://data.police.uk/api/crimes-street/all-crime?lat=52.629729&lng=-1.131592&date=2019-10";
  const { data, error } = useSWR(url);
 
  if (error) return <div>Error...</div>;
  if (!data) return <div>Loading...</div>;
 
  return (
    <DisplayCrimes
      crimes={data}
      categories={[...new Set(data.map((crime) => crime.category))]}
    />
  );
}

Unique Values in JavaScript

In order to display (and filter) the crime data, I want a unique list of the crime categories. JavaScript doesn't have a way to do this out of the box like you might do values.uniq in Ruby. We can make our own very quickly though using a Set.

// find all categories
const allCategories = data.map((crime) => crime.category);
// convert all categories into a set
const categorySet = new Set(allCategories);
// convert set back to an array
const categories = [...categorySet];
 
// final/shortened solution
[...new Set(data.map((crime) => crime.category))];

Displaying & Filtering Data

Displaying the data really has nothing to do with SWR at this point, but that is sort of the point. The display logic shouldn't really care where the data comes from, only how to display it to the user.

We will keep track of a filterCategory if the user wants only a subset of all the crimes, producing a filtered list of crimes using the array filter function.

function DisplayCrimes({ crimes, categories }) {
  const [filterCategory, setFilterCategory] = React.useState(null);
  const filteredCrimes = filterCategory
    ? crimes.filter((crime) => crime.category === filterCategory)
    : crimes;
 
  return (
    <>
      {categories.map((category) => (
        <button
          onClick={() => {
            setFilterCategory(category);
          }}
          key={category}
        >
          {category}
        </button>
      ))}
      {filterCategory && (
        <button
          onClick={() => {
            setFilterCategory(null);
          }}
        >
          reset
        </button>
      )}
 
      <pre>{JSON.stringify(filteredCrimes, null, 2)}</pre>
    </>
  );
}

Conclusion

Based on my experience with the SWR package, I think it would be my go-to approach when working with RESTful APIs in React. That said, I don't think I would switch from Apollo if my data were coming from GraphQL. Apollo provides a lot of nice utilities specific to GraphQL that you wouldn't get with SWR, which admittedly is a lower-level tool that you could build on top of.