30 lines
669 B
TypeScript
30 lines
669 B
TypeScript
|
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,
|
||
|
};
|
||
|
}
|