1π
But when I try to get the user in useEffect, it returns undefined.
Havenβt you just forgot to include currentUser
in the dependecy array?
const { currentUser } = useContext(AuthContext);
const ref = useRef(false);
useEffect(()=> {
if (!ref.current) return;
if (currentUser) {
ref.current = true;
chatSocket.onmessage = function(e) {
console.log(currentUser)
const data = JSON.parse(e.data);
setMessages(old => [...old, <p ref={oneRef} className={currentUser[0]?.username}>{data.message}</p>])
};
}
}, [currentUser])
π€kind user
0π
As kinduser said I just added currentUser
as dependacy. And because the messages were duplicated I solved it with a cleanup function. So now the code looks like this.
useEffect(()=> {
let ran = true;
chatSocket.onmessage = function(e) {
if (ran == true) {
console.log(checker)
const data = JSON.parse(e.data);
setMessages(old => [...old, <p ref={oneRef} className={currentUser[0]?.username}>{data.message}</p>])
setChecker(false)
}
}
return () => {
ran = false;
};
},[currentUser])
π€zequuee1
Source:stackexchange.com