import { Accessor, createSignal } from "solid-js" import { EmptyResp, PResp } from "~/types" export const useLoading = ( p: (...arg: any[]) => Promise, fetch?: boolean, t?: boolean, // initial loading true ): [ Accessor, (...arg: any[]) => Promise, ] => { const [loading, setLoading] = createSignal(t ?? false) return [ loading, async (...arg: any[]) => { setLoading(true) const data = await p(...arg) if (!fetch || (data as unknown as EmptyResp).code !== 401) { // why? // because if setLoading(false) here will rerender before navigate // maybe cause some bugs setLoading(false) } return data }, ] } export const useFetch = ( p: (...arg: any[]) => PResp, loading?: boolean, ): [ Accessor, (...arg: Parameters) => PResp, ] => { return useLoading(p, true, loading) } const useListLoading = ( p: (key: K, ...arg: any[]) => Promise, fetch?: boolean, initial?: K, ): [Accessor, (key: K, ...arg: any[]) => Promise] => { const [loading, setLoading] = createSignal(initial) return [ loading, async (key: K, ...arg: any[]) => { setLoading(() => key) const data: unknown = await p(key, ...arg) if (!fetch || (data as EmptyResp).code !== 401) { setLoading(undefined) } return data }, ] } export const useListFetch = ( p: (key: K, ...arg: any[]) => PResp, initial?: K, ): [Accessor, (key: K, ...arg: any[]) => Promise] => { return useListLoading(p, true, initial) }