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>;
}
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
};
};
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.