fix(NotificationContext): handle user ID for notifications fetching and prevent stale responses
All checks were successful
Build & Push Docker Image / build (push) Successful in 6m6s
All checks were successful
Build & Push Docker Image / build (push) Successful in 6m6s
This commit is contained in:
@@ -49,14 +49,20 @@ export function NotificationProvider({ children }) {
|
|||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const [notifications, setNotifications] = useState([]);
|
const [notifications, setNotifications] = useState([]);
|
||||||
const [unreadCount, setUnreadCount] = useState(0);
|
const [unreadCount, setUnreadCount] = useState(0);
|
||||||
|
const activeUserId = useRef(null);
|
||||||
// Track seen IDs to detect genuinely new arrivals and show toasts
|
// Track seen IDs to detect genuinely new arrivals and show toasts
|
||||||
const seenIds = useRef(new Set());
|
const seenIds = useRef(new Set());
|
||||||
const initialized = useRef(false);
|
const initialized = useRef(false);
|
||||||
|
|
||||||
const fetch = useCallback(async () => {
|
const fetch = useCallback(async () => {
|
||||||
if (!user) return;
|
const requestUserId = user?.id;
|
||||||
|
if (!requestUserId) return;
|
||||||
try {
|
try {
|
||||||
const res = await api.get('/notifications');
|
const res = await api.get('/notifications');
|
||||||
|
|
||||||
|
// Ignore stale responses that arrived after logout or account switch.
|
||||||
|
if (activeUserId.current !== requestUserId) return;
|
||||||
|
|
||||||
const incoming = res.data.notifications || [];
|
const incoming = res.data.notifications || [];
|
||||||
setNotifications(incoming);
|
setNotifications(incoming);
|
||||||
setUnreadCount(res.data.unreadCount || 0);
|
setUnreadCount(res.data.unreadCount || 0);
|
||||||
@@ -106,6 +112,7 @@ export function NotificationProvider({ children }) {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
activeUserId.current = user?.id ?? null;
|
||||||
if (!user) {
|
if (!user) {
|
||||||
setNotifications([]);
|
setNotifications([]);
|
||||||
setUnreadCount(0);
|
setUnreadCount(0);
|
||||||
|
|||||||
Reference in New Issue
Block a user