I am coding a chat app with django channels and react. I want when a new message is send, to have a className of the current user.
I already have the current user in context so I just have to call it and get it. But when I try to get the user in useEffect, it returns {}.
const {currentUser} = useContext(AuthContext)
useEffect(()=> {
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>])
};
},[])
Also I need the useEffect
so I can’t just remove it. I don’t wanna to call an axios
call every time a new message is sended. And the currentUser
is an object.
2
Answers
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.Haven’t you just forgot to include
currentUser
in the dependecy array?