// @todo: sample composable
import { ref, watch, toValue, MaybeRefOrGetter } from "vue";

export const useSampleFetch = <T>(
  initialId: MaybeRefOrGetter<string>,
  fetcher: (id: string) => Promise<T>,
) => {
  const data = ref<T>();
  const error = ref();
  const isLoading = ref(false);

  async function fetchData(id: string) {
    try {
      isLoading.value = true;
      data.value = undefined;
      error.value = undefined;
      data.value = await fetcher(id);
    } catch (err) {
      error.value = err;
    } finally {
      isLoading.value = false;
    }
  }

  watch(() => toValue(initialId), fetchData);

  return {
    id: initialId,
    data,
    error,
    isLoading,
  };
};
