Skip to content

Instantly share code, notes, and snippets.

@dps
Created September 2, 2024 05:38
Show Gist options
  • Save dps/59c75b3bfaaa81ed2e92f4863ce758db to your computer and use it in GitHub Desktop.
Save dps/59c75b3bfaaa81ed2e92f4863ce758db to your computer and use it in GitHub Desktop.
useItemsByOwner with async updates
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