skip to Main Content

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


  1. Chosen as BEST ANSWER

    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])
    

  2. 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])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search