[Answered ]-React useContext is undefined in useeffect

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

Leave a comment