Handling Realtime Data with Supabase
In this guide, we'll learn how to handle realtime data in Supabase using server actions and react query. We implemented notifications as a realtime feature in Nextbase Ultimate and we can use that as a reference.
Supabase Realtime
Supabase provides a realtime service which can be used to listen to changes in your database. When used with a React client component useEffect it looks something like this:
import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query';
import {
getPaginatedNotifications,
getUnseenNotificationIds,
readAllNotifications,
seeNotification,
} from './fetchClientNotifications';
const useUnseenNotificationIds = (userId: string) => {
const { data, refetch } = useQuery(
['unseen-notification-ids', userId],
async () => {
return getUnseenNotificationIds(userId);
},
{
initialData: [],
},
);
useEffect(() => {
const channelId = `user-notifications:${userId}`;
const channel = supabaseClient
.channel(channelId)
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'user_notifications',
filter: 'user_id=eq.' + userId,
},
() => {
refetch();
},
)
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'user_notifications',
filter: 'user_id=eq.' + userId,
},
(payload) => {
refetch();
},
)
.subscribe();
return () => {
channel.unsubscribe();
};
}, [refetch, userId]);
In the above code, we are listening to changes in the user_notifications
table and refetching the data when a change occurs.
Depending on the scenario, you can also just use the payload from the realtime data to setState
or update a react query
cache directly.