Created
July 13, 2024 21:21
-
-
Save mamodev/2f4d35616be0f3b41fe3f73a47c16699 to your computer and use it in GitHub Desktop.
Simple hook for any query of a supabase client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { | |
PostgrestBuilder, | |
PostgrestFilterBuilder, | |
} from "@supabase/postgrest-js"; | |
import { GenericSchema } from "@supabase/supabase-js/dist/module/lib/types"; | |
type GenericBuilder = PostgrestBuilder<unknown> | PostgrestFilterBuilder<GenericSchema, Record<string, unknown>, unknown>; | |
type State<T extends GenericBuilder> = { | |
data: Awaited<T>["data"] | null; | |
error: Awaited<T>["error"] | null; | |
isLoading: boolean; | |
}; | |
export function useQuery<T extends GenericBuilder>(query: T) { | |
const url = (query as unknown as { url: URL }).url.toString(); | |
const [state, setState] = React.useState<State<T>>({ | |
data: null, | |
error: null, | |
isLoading: true, | |
}); | |
React.useEffect(() => { | |
const ac = new AbortController(); | |
(query as PostgrestFilterBuilder<GenericSchema, Record<string, unknown>, unknown>) | |
.abortSignal(ac.signal) | |
.then((res) => setState({ data: res.data, error: res.error, isLoading: false })); | |
return () => ac.abort(); | |
}, [url]); | |
return state; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment