Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active April 30, 2022 04:14
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save WebReflection/dea6cd9ab50e61ec14202a416cd6d121 to your computer and use it in GitHub Desktop.
Save WebReflection/dea6cd9ab50e61ec14202a416cd6d121 to your computer and use it in GitHub Desktop.

What's SWR?

It's React Hooks for Remote Data Fetching, a hook designed to render data on demand.

import useSWR from 'swr'

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher);

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;
  return <div>hello {data.name}!</div>;
}

OK cool, how can I have it outside React?

Well, you need a hook, and this is the most basic one for one-off visualization:

const swr = new Set;

const useSWR = (path, fetcher) => {
  let [data, update] = useState(null);
  if (!swr.has(path)) {
    fetcher(path).then(update, () => update(new Error(path)));
    swr.add(path);
  }
  const isError = data instanceof Error;
  return {
    data: isError ? null : data,
    error: isError ? data : null
  };
};

But this one allows cache invalidation, in case the time is right to re-fetch the data:

const swr = new Map;

const useSWR = (path, fetcher, cache) => {
  let [data, update] = useState(null);
  if (!swr.has(path) || swr.get(path) !== cache) {
    fetcher(path).then(update, () => update(new Error(path)));
    swr.set(path, cache);
  }
  const isError = data instanceof Error;
  return {
    data: isError ? null : data,
    error: isError ? data : null
  };
};

Which libarry can use this hook?

At least any of my libarries based on uhooks.

import {Component, html, useState} from 'uland';

const fetcher = url => fetch(url).then(r => r.json());

const Profile = Component(() => {
  const {data, error} = useSWR(url, fetcher);
  if (error) return html`<div>failed to load</div>`;
  if (!data) return html`<div>loading...</div>`;
  return html`<div>hello {data.name}!</div>`;
});

You can find a Codepen uland example using this pattern.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment