Subscribe the UI to Database Changes with Supabase Real-Time

Jon Meyers
InstructorJon Meyers

Share this video with your friends

Send Tweet
Published a month ago
Updated 8 hours ago

The cancellation event from stripe doesn't get triggered until the end of the billing cycle. Therefore, our customer may still be using our app when their subscription status changes, with their dashboard confusingly displaying the incorrect data.

In this video, we implement Supabase real-time to subscribe the UI to changes in the database. We can initiate the subscription in our useUser hook, and specify that we only care about updates to our currently logged in user.

In order for Supabase to broadcast these changes on our websocket connection, we need to enable replication for the specific tables we want to subscribe to.

This means that anytime our is_subscribed value changes in the profile table, our useUser hook will automatically be updated with the new value, and the dashboard will immediately update to display the correct data.

Instructor: [0:00] Since this cancellation event doesn't happen until the end of the billing cycle, our user may still be using our application and think that they're subscribed. It isn't until they refresh the application that they see that that state has changed. Let's use Supabase Realtime to update our UI as soon as this change happens.

[0:16] We can do that by going to our Supabase dashboard and then Database, Replication and then telling it which tables we'd like to turn this on for. We're going to enable our Profile table. Now, back in our application, we can open up our user provider and call useEffect() again.

[0:30] We want this callback to trigger any time our user object changes. Now, if we have a user, we can create a new subscription by saying supabase. from the Profile table. We specifically only want to listen to changes where the ID is equal to our user's ID.

[0:45] We can then specify which database events we actually care about, so, in this case, just UPDATE, and then we provide a callback, which it will call and parse a payload object containing all of the changes of our update. Then we can call setUser(), spread in the current state of our user, and then spread in anything that's changed from payload.new.

[1:04] We can then call subscribe() and then return an arrow function to clean up this subscription by calling Supabase.removeSubscription() and giving it our subscription. Now, if we subscribe our user again, then cancel their subscription in Stripe, we'll see that that field is immediately updated in the user's dashboard without requiring a refresh.