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,
  options?: RequestInit
) {
  const data = writable<D | undefined>();
  const error = writable<E | undefined>();

  async function doFetch() {
    try {
      const response = await fetch(key, options);
      if (response.ok) {
        data.set(await response.json());
      } else {
        let errorText = `${response.status} ${response.statusText}`;
        const responseText = await response.text();
        if (responseText) {
          errorText += ` - ${responseText}`;
        }
        throw new Error(errorText);
      }
    } catch (err) {
      error.set(err);
    }
  }

  doFetch();

  return {
    data,
    error,
    revalidate: doFetch,
  };
}
