'use client' import { PostgrestQueryBuilder, type PostgrestClientOptions } from '@supabase/postgrest-js' import { type SupabaseClient } from '@supabase/supabase-js' import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react' import { createClient } from '@/registry/default/fixtures/lib/supabase/client' const supabase = createClient() // The following types are used to make the hook type-safe. It extracts the database type from the supabase client. type SupabaseClientType = typeof supabase // Utility type to check if the type is any type IfAny = 0 extends 1 & T ? Y : N // Extracts the database type from the supabase client. If the supabase client doesn't have a type, it will fallback properly. type Database = SupabaseClientType extends SupabaseClient ? IfAny< U, { public: { Tables: Record Views: Record Functions: Record } }, U > : { public: { Tables: Record Views: Record Functions: Record } } // Change this to the database schema you want to use type DatabaseSchema = Database['public'] // Extracts the table names from the database type type SupabaseTableName = keyof DatabaseSchema['Tables'] // Extracts the table definition from the database type type SupabaseTableData = DatabaseSchema['Tables'][T]['Row'] // Default client options for PostgrestQueryBuilder type DefaultClientOptions = PostgrestClientOptions type SupabaseSelectBuilder = ReturnType< PostgrestQueryBuilder< DefaultClientOptions, DatabaseSchema, DatabaseSchema['Tables'][T], T >['select'] > // A function that modifies the query. Can be used to sort, filter, etc. If .range is used, it will be overwritten. type SupabaseQueryHandler = ( query: SupabaseSelectBuilder ) => SupabaseSelectBuilder interface UseInfiniteQueryProps { // The table name to query tableName: T // The columns to select, defaults to `*` columns?: string // The number of items to fetch per page, defaults to `20` pageSize?: number // A function that modifies the query. Can be used to sort, filter, etc. If .range is used, it will be overwritten. trailingQuery?: SupabaseQueryHandler // Optional key that identifies the current trailing query shape (e.g. filters/sort/search). // When this changes, the internal store is recreated so stale paginated rows are discarded. trailingQueryKey?: unknown } interface StoreState { data: TData[] count: number isSuccess: boolean isLoading: boolean isFetching: boolean error: Error | null hasInitialFetch: boolean } type Listener = () => void interface StoreProps { tableName: T columns?: string pageSize?: number getTrailingQuery: () => SupabaseQueryHandler | undefined } function createStore, T extends SupabaseTableName>( props: StoreProps ) { const { tableName, columns = '*', pageSize = 20, getTrailingQuery } = props let state: StoreState = { data: [], count: 0, isSuccess: false, isLoading: false, isFetching: false, error: null, hasInitialFetch: false, } const listeners = new Set() const notify = () => { listeners.forEach((listener) => listener()) } const setState = (newState: Partial>) => { state = { ...state, ...newState } notify() } const fetchPage = async (skip: number) => { if (state.hasInitialFetch && (state.isFetching || state.count <= state.data.length)) return setState({ isFetching: true }) let query = supabase .from(tableName) .select(columns, { count: 'exact' }) as unknown as SupabaseSelectBuilder const trailingQuery = getTrailingQuery() if (trailingQuery) { query = trailingQuery(query) } const { data: newData, count, error } = await query.range(skip, skip + pageSize - 1) if (error) { console.error('An unexpected error occurred:', error) setState({ error }) } else { setState({ data: [...state.data, ...(newData as TData[])], count: count || 0, isSuccess: true, error: null, }) } setState({ isFetching: false }) } const fetchNextPage = async () => { if (state.isFetching) return await fetchPage(state.data.length) } const initialize = async () => { setState({ isLoading: true, isSuccess: false, data: [] }) await fetchNextPage() setState({ isLoading: false, hasInitialFetch: true }) } return { getState: () => state, subscribe: (listener: Listener) => { listeners.add(listener) return () => listeners.delete(listener) }, fetchNextPage, initialize, } } // Empty initial state to avoid hydration errors. const initialState: any = { data: [], count: 0, isSuccess: false, isLoading: false, isFetching: false, error: null, hasInitialFetch: false, } function useInfiniteQuery< TData extends SupabaseTableData, T extends SupabaseTableName = SupabaseTableName, >(props: UseInfiniteQueryProps) { const tableName = props.tableName const columns = props.columns ?? '*' const pageSize = props.pageSize ?? 20 const trailingQuery = props.trailingQuery const trailingQueryKey = props.trailingQueryKey const trailingQueryRef = useRef(trailingQuery) trailingQueryRef.current = trailingQuery const store = useMemo( () => createStore({ tableName, columns, pageSize, getTrailingQuery: () => trailingQueryRef.current, }), [tableName, columns, pageSize, trailingQueryKey] ) const state = useSyncExternalStore( store.subscribe, () => store.getState(), () => initialState as StoreState ) useEffect(() => { if (!state.hasInitialFetch && typeof window !== 'undefined') { store.initialize() } }, [state.hasInitialFetch, store]) return { data: state.data, count: state.count, isSuccess: state.isSuccess, isLoading: state.isLoading, isFetching: state.isFetching, error: state.error, hasMore: state.count > state.data.length, fetchNextPage: store.fetchNextPage, } } export { useInfiniteQuery, type SupabaseQueryHandler, type SupabaseTableData, type SupabaseTableName, type UseInfiniteQueryProps, }