Skip to content

Instantly share code, notes, and snippets.

@mamodev
Created July 13, 2024 21:21
Show Gist options
  • Save mamodev/2f4d35616be0f3b41fe3f73a47c16699 to your computer and use it in GitHub Desktop.
Save mamodev/2f4d35616be0f3b41fe3f73a47c16699 to your computer and use it in GitHub Desktop.
Simple hook for any query of a supabase client
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