Replies: 1 comment
-
Ah found something that will work for now.
import { useEffect, useState } from 'react'
import PostgrestFilterBuilder from '@supabase/postgrest-js/dist/main/lib/PostgrestFilterBuilder'
import { definitions } from 'types/supabase'
import { supabase } from '@/utils/initSupabase'
export function useSupabaseSubscription<T extends keyof definitions>(
table: T,
selectQuery: PostgrestFilterBuilder<definitions[T]>
): {
data: definitions[T][]
count: number | null
loading: boolean
error: boolean
} {
const [loading, setLoading] = useState(true)
const [error, setError] = useState(false)
const [data, setData] = useState<definitions[T][]>([])
const [count, setCount] = useState<number | null>(null)
const fetch = async () => {
const { data: items, count, error } = await selectQuery
if (error) {
setError(true)
console.log('error', error)
}
if (items) {
setData(items)
setCount(count)
}
setLoading(false)
return
}
useEffect(() => {
fetch()
}, [selectQuery])
useEffect(() => {
const subscription = supabase
.from<definitions[T]>(table)
.on('*', fetch)
.subscribe()
return () => {
subscription.unsubscribe()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return { data, count, loading, error }
}
const { data } = useSupabaseSubscription<'TableName'>(
'TableName',
supabase.from('TableName').select('*').order('id', { ascending: true })
) Although I'd still like to prevent calling any other method then I'll update this thread if I found a way to improve this, so that it might help others :) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi guys,
I'm trying to create a general React hook to fetch items from a table and add a subscription. Maybe it's more of a Typescript related question than a Supabase one, but I'm trying anyway :)
Below my hook so far, 'only' thing I'm stuck on is that I want to have the 'query' part (so after
supabase.from()
...) to be accepted as a variable, and only acceptselect()
queries for this variable.Has someone tried this before?
For reference; I'm using
swagger-to-ts
to generate my types (https://supabase.io/docs/client/generating-types)Beta Was this translation helpful? Give feedback.
All reactions