this is my first question, so basically i’ve a notification object and I’ve attached a firebase onValue listners which fires the handleNotification function everytime a new value is being added, problem is that the handleNotification fn is not using the updated notification state
const [notification, setNotification] = useState({
id: '',
total: '',
lastTotal: '',
count: '',
});
const handleNotification = (channelId, snap, notification) => {
console.log('notification before -------', notification);
if (notification.id === '') {
let obj = {
id: channelId,
total: snap.size,
lastKnownTotal: snap.size,
count: 0,
};
setNotification({ ...obj });
return console.log('notification after -------', notification);
}
// the above if statement runs even when notification.id is already populated, the below code should run instead of that
let obj2 = {
...notification,
};
if (snap.size - obj2.total > 0) {
setNotification((prev) => ({ ...prev, count: snap.size - obj2.total }));
}
};
useEffect(() => {
const unsubscribe = onValue(
ref(db, 'messages' + '/' + channel.id),
(snap) => {
if (channel) {
handleNotification(channel.id, snap, notification);
} else {
console.log('////');
}
}
);
return () => {
unsubscribe();
};
}, []);