ready to test
Testing Signed-off-by: Kenneth Obsequio <k80308392@gmail.com>
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
|
||||
import api from "@/utils/api.util";
|
||||
|
||||
const ClientNotificationContext = createContext(null);
|
||||
|
||||
const POLL_INTERVAL = 60_000;
|
||||
|
||||
export function useClientNotifications() {
|
||||
const ctx = useContext(ClientNotificationContext);
|
||||
if (!ctx) throw new Error("useClientNotifications must be used within ClientNotificationProvider");
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function ClientNotificationProvider({ children }) {
|
||||
const [notifications, setNotifications] = useState([]);
|
||||
const [unseenCount, setUnseenCount] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const intervalRef = useRef(null);
|
||||
|
||||
const fetchUnseen = useCallback(async () => {
|
||||
try {
|
||||
const res = await api.get("/client/notifications/unseen");
|
||||
setUnseenCount(res.data?.data?.count ?? 0);
|
||||
} catch {
|
||||
// silent — badge stays at last known count
|
||||
}
|
||||
}, []);
|
||||
|
||||
const fetchNotifications = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.get("/client/notifications?limit=20");
|
||||
const rows = res.data?.data?.notifications ?? [];
|
||||
setNotifications(rows);
|
||||
setUnseenCount(rows.filter(n => !n.seen).length);
|
||||
} catch {
|
||||
// silent
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const markSeen = useCallback(async (id) => {
|
||||
try {
|
||||
await api.patch(`/client/notifications/${id}/seen`);
|
||||
setNotifications(prev =>
|
||||
prev.map(n => n.notification_id === id ? { ...n, seen: true } : n)
|
||||
);
|
||||
setUnseenCount(prev => Math.max(0, prev - 1));
|
||||
} catch {
|
||||
// silent
|
||||
}
|
||||
}, []);
|
||||
|
||||
const markAllSeen = useCallback(async () => {
|
||||
try {
|
||||
await api.patch("/client/notifications/seen-all");
|
||||
setNotifications(prev => prev.map(n => ({ ...n, seen: true })));
|
||||
setUnseenCount(0);
|
||||
} catch {
|
||||
// silent
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUnseen();
|
||||
intervalRef.current = setInterval(fetchUnseen, POLL_INTERVAL);
|
||||
return () => clearInterval(intervalRef.current);
|
||||
}, [fetchUnseen]);
|
||||
|
||||
return (
|
||||
<ClientNotificationContext.Provider value={{
|
||||
notifications,
|
||||
unseenCount,
|
||||
loading,
|
||||
fetchNotifications,
|
||||
markSeen,
|
||||
markAllSeen,
|
||||
}}>
|
||||
{children}
|
||||
</ClientNotificationContext.Provider>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user