ColdC
Reactiflux15mo ago
62 replies
Cold

State not getting updated

I have a project I'm working on currently where I am using zustand for state management. I switched to zustand after encountering similar problems with base state management, but clearly this hasn't helped. I am trying to create a live notification/account update system, where the client uses server-sent events to manage this. The server will send an update every 5 seconds. Now, in the code below, I am very clearly updating the state with this data, but it is not doing anything. Can anyone help me figure out why and help me fix it?
Solution
Here is what I did:
    const { notifications, setNotifications } = useNotificationStore();
    const [localNotifications, setLocalNotifications] = useState<
        Notification[]
    >([]);
    const { warnings, setWarnings } = useWarningStore();
    const [loading, setLoading] = useState(true);
    const router = useRouter();

    useEffect(() => {
        const existingUUIDs = new Set(
            notifications?.map((notification) => notification.uuid),
        );
        localNotifications.forEach(
            (notification) =>
                (notification.shouldNotify = !existingUUIDs.has(
                    notification.uuid,
                )),
        );
        setNotifications(localNotifications);
    }, [localNotifications]);

    useEffect(() => {
        if (!loading && user) {
            const eventSource = new EventSource(
                process.env.NEXT_PUBLIC_BACKEND_URI + "/users/@me/events",
                {
                    withCredentials: true,
                },
            );

            eventSource.onerror = (error) => {
                console.error("EventSource failed: ", error);
                eventSource.close();
            };

            eventSource.onmessage = (event) => {
                const data = JSON.parse(event.data);

                if (user) {
                    setLocalNotifications(data.notifications);
                    setWarnings(data.warnings);

                    setUser({
                        ...user,
                        banned: data.banned,
                        limited: data.limited,
                    });
                } else eventSource.close();
            };

            return () => eventSource.close();
        }
    }, [loading]);
Was this page helpful?