Files
supabase/apps/ui-library/registry/default/blocks/infinite-query-hook/hooks/use-infinite-query.ts
Vaibhav 7b8be519bb fix: reset stale infinite query (#44810)
fixes `UseInfiniteQuery` so it recreates when query inputs change

the previous prop change check compared values to themselves so the hook
could keep stale paginated state
after table columns page size or trailing query changed

- closes https://github.com/supabase/supabase/issues/37750


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added an optional trailingQueryKey prop to the infinite-query hook to
better control when its internal store is refreshed.

* **Bug Fixes**
* Pagination now reliably uses the latest trailing query and avoids
inconsistent state during initial load and subsequent pages.

* **Refactor**
* Reworked store lifecycle and initialization for the infinite-query
hook to reduce unnecessary recreations, streamline startup, and improve
performance and stability.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-06-02 12:16:39 +02:00

241 lines
6.5 KiB
TypeScript

'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<T, Y, N> = 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<infer U>
? IfAny<
U,
{
public: {
Tables: Record<string, any>
Views: Record<string, any>
Functions: Record<string, any>
}
},
U
>
: {
public: {
Tables: Record<string, any>
Views: Record<string, any>
Functions: Record<string, any>
}
}
// 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<T extends SupabaseTableName> = DatabaseSchema['Tables'][T]['Row']
// Default client options for PostgrestQueryBuilder
type DefaultClientOptions = PostgrestClientOptions
type SupabaseSelectBuilder<T extends SupabaseTableName> = 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<T extends SupabaseTableName> = (
query: SupabaseSelectBuilder<T>
) => SupabaseSelectBuilder<T>
interface UseInfiniteQueryProps<T extends SupabaseTableName, Query extends string = '*'> {
// 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<T>
// 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<TData> {
data: TData[]
count: number
isSuccess: boolean
isLoading: boolean
isFetching: boolean
error: Error | null
hasInitialFetch: boolean
}
type Listener = () => void
interface StoreProps<T extends SupabaseTableName> {
tableName: T
columns?: string
pageSize?: number
getTrailingQuery: () => SupabaseQueryHandler<T> | undefined
}
function createStore<TData extends SupabaseTableData<T>, T extends SupabaseTableName>(
props: StoreProps<T>
) {
const { tableName, columns = '*', pageSize = 20, getTrailingQuery } = props
let state: StoreState<TData> = {
data: [],
count: 0,
isSuccess: false,
isLoading: false,
isFetching: false,
error: null,
hasInitialFetch: false,
}
const listeners = new Set<Listener>()
const notify = () => {
listeners.forEach((listener) => listener())
}
const setState = (newState: Partial<StoreState<TData>>) => {
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<T>
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>,
T extends SupabaseTableName = SupabaseTableName,
>(props: UseInfiniteQueryProps<T>) {
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<TData, T>({
tableName,
columns,
pageSize,
getTrailingQuery: () => trailingQueryRef.current,
}),
[tableName, columns, pageSize, trailingQueryKey]
)
const state = useSyncExternalStore(
store.subscribe,
() => store.getState(),
() => initialState as StoreState<TData>
)
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,
}