Skip to content

Commit

Permalink
feature: populate initial notifications and add new ones upon being a…
Browse files Browse the repository at this point in the history
…dded to the db
  • Loading branch information
mr3nz1 committed Jul 19, 2024
1 parent 719e17b commit 8b9fbe3
Showing 1 changed file with 52 additions and 3 deletions.
55 changes: 52 additions & 3 deletions ctx/NotificationsContext.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { supabase } from "@/lib/supabase";
import React, { createContext, useContext, useEffect, useState } from "react";

export interface NotificationsType {
Expand All @@ -14,6 +15,7 @@ export interface NotificationType {
description: string;
createdAt: Date;
patientId: string;
viewed: boolean;
}

export const NotificationsContext = createContext<NotificationsType>({
Expand Down Expand Up @@ -44,9 +46,56 @@ export default function NotificationsProvider({ children }: Props) {
}

useEffect(() => {
console.log("##########################");
console.log("Notifications context");
console.log("##########################");
const fetchInitialNotifications = async () => {
const { data, error } = await supabase
.from("patient_notifications")
.select("*");

if (error) {
console.error("Error fetching notifications:", error);
} else {
const notifs = data.map((notification) => {
return {
id: notification.id,
createdAt: notification.created_at,
title: notification.title,
description: notification.description,
patientId: notification.patient_id,
viewed: notification.viewed,
};
});

setNotifications(notifs || []);
}
};

fetchInitialNotifications();

const channel = supabase
.channel("patient_notifications")
.on(
"postgres_changes",
{ event: "INSERT", schema: "public" },
(payload) => {
const newNotification = payload.new;
setNotifications((prevNotifications) => [
...prevNotifications,
{
id: newNotification.id,
createdAt: newNotification.created_at,
title: newNotification.title,
description: newNotification.description,
patientId: newNotification.patient_id,
viewed: newNotification.viewed,
},
]);
}
)
.subscribe();

return () => {
supabase.removeChannel(channel);
};
}, []);

const value = {
Expand Down

0 comments on commit 8b9fbe3

Please sign in to comment.