upend/ui/src/util/fetch.ts

30 lines
669 B
TypeScript
Raw Normal View History

2021-11-11 23:37:42 +01:00
import { writable } from "svelte/store";
// stale shim until https://github.com/ConsoleTVs/sswr/issues/24 is resolved
export type SWRKey = string;
export function useSWR<D = unknown, E = Error>(
key: SWRKey | undefined | (() => SWRKey | undefined)
) {
const data = writable<D | undefined>();
const error = writable<D | undefined>();
function doFetch() {
let keyString = typeof key === "string" ? key : key();
fetch(keyString)
.then(async (response) => {
data.set(await response.json());
})
.catch((err) => {
error.set(err);
});
}
doFetch();
return {
data,
error,
revalidate: doFetch,
};
}