Created
September 2, 2024 05:38
-
-
Save dps/59c75b3bfaaa81ed2e92f4863ce758db to your computer and use it in GitHub Desktop.
useItemsByOwner with async updates
This file contains hidden or 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 { | |
useQuery, | |
useQueryClient, | |
QueryClient, | |
QueryClientProvider as QueryClientProviderBase, | |
} from "react-query"; | |
import { useEffect } from "react"; | |
import supabase from "./supabase"; | |
//... omitted other stuff ... | |
// Fetch all items by owner | |
export function useItemsByOwner(owner) { | |
const queryClient = useQueryClient(); | |
const queryKey = ["items", { owner }]; | |
// Fetch the items using React Query | |
const itemsQuery = useQuery( | |
queryKey, | |
() => | |
supabase | |
.from("items") | |
.select() | |
.eq("owner", owner) | |
.order("createdAt", { ascending: false }) | |
.then((res) => res.data), | |
{ enabled: !!owner } | |
); | |
useEffect(() => { | |
if (!owner) return; | |
// Setup real-time subscription for the items table | |
const subscription = supabase | |
.channel("public:items") | |
.on( | |
"postgres_changes", | |
{ | |
event: "*", | |
schema: "public", | |
table: "items", | |
filter: `owner=eq.${owner}`, | |
}, | |
(payload) => { | |
// Invalidate and refetch the query when a change is detected | |
queryClient.invalidateQueries(queryKey); | |
} | |
) | |
.subscribe(); | |
// Cleanup subscription on unmount | |
return () => { | |
supabase.removeChannel(subscription); | |
}; | |
}, [owner, queryClient]); | |
return itemsQuery; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment