skip to Main Content

i am creating a chat application, where message variable is coming from another component. i want to filter the messages according to their room id

so i used useEffect to update the roomMessage variable everytime message updates. the message variable updates, but the roomMessage is not updating and the new messages are not showing in the screen. is it the filter() function’s problem or what?

export default function Chat_body() {

///messages has all the message data
    let {userName,userID,messages} = useContext(AuthContext);

    const {roomID} = useParams();
    const [roomMessages,setRoomMessages] = useState(messages.filter((message) => message.room === parseInt(roomID)).reverse())

     useEffect(() => {
        
         setRoomMessages(messages.filter((message) => message.room === parseInt(roomID)).reverse())
         console.log(roomMessages)

       }, [roomID,messages]);

      

      
   

  return (
    <div className="chat_body">

        {roomMessages.map((message)=>{
            
            return(

                
                
      {roomMessages.map((message)=>{
            
            return(

                
                
        <div key={message.id} className={userName===message.sender ? "chat_message recieved" :"chat_message"}>
            <span className='avatar_span'><MdAccountCircle/></span>
            <div className={userName===message.sender ? "message chat_recieved" : "message"}>
                <span className='chat_name'>{message.sender}</span>
                <div className={userName===message.sender ? "sent_message  chat_reciever" : "sent_message"}>
                    <p>{message.message}</p>
                    <span className='timeSpan'>{message.sent_at}</span>
                </div>
            </div>
        </div>
                )

        })}
    )
}

context.js

import React,{createContext,useState,useEffect} from 'react'
import jwt_decode from "jwt-decode";
import { useNavigate } from 'react-router-dom';
import pusherJs from 'pusher-js';


const endpointMessage = 'http://127.0.0.1:8000/message'
 const [messages,setMessages] = useState([])



 useEffect(()=>{
     const pusher = new pusherJs('f12d9df33bdc80d7947b', {
      cluster: 'ap2'
    });

    var channel = pusher.subscribe('chat');
    channel.bind('message', function(data) {
      setMessages([...messages,data]);
      console.log(messages)
    });

    return ()=>{
      channel.unbind_all();
      channel.unsubscribe();
    }
  },[messages])

if I map the message variable, all the messages shows, and renders the updated messages as well but when I try to filter them, the new messages doesn’t show!

3

Answers


  1. Chosen as BEST ANSWER

    I have figured it out. the problem was that, the datatype of roomID received by useParams and the message.room wasn't the same. which is why, everytime I was filtering with the condition of

    message.room === roomID
    

    it was not returning true. i had to make it

    prevMessage.filter(message => message.room == parseInt(roomID).reverse())
    

    with "==" to make it work. I am extremely sorry for giving everyone a hard time for such stupid mistake and thank you all for helping me out.


  2. useEffect(() => {
      setRoomMessages( prevMessage => {
        return prevMessage.filter(message => message.room === parseInt(roomID).reverse())
      })
      console.log(roomMessages)
    }, [roomID,messages]);
    
    Login or Signup to reply.
  3. Just remove the useState and useEffect hooks from Chat_body component and filter the messages from the context directly. (You also have used map twice, which is not needed). It should look something like this:

    export default function Chat_body() {
      ///messages has all the message data
      let { userName, messages } = useContext(AuthContext);
    
      const { roomID } = useParams();
    
      const filteredMessages = messages.filter((message) => message.room === parseInt(roomID)).reverse();
      const isSender = userName === message.sender;
    
      return (
        <div className="chat_body">
          {filteredMessages.map((message) => (
            <div key={message.id} className={isSender ? 'chat_message recieved' : 'chat_message'}>
              <span className="avatar_span">
                <MdAccountCircle />
              </span>
    
              <div className={isSender ? 'message chat_recieved' : 'message'}>
                <span className="chat_name">{message.sender}</span>
    
                <div className={isSender ? 'sent_message  chat_reciever' : 'sent_message'}>
                  <p>{message.message}</p>
                  <span className="timeSpan">{message.sent_at}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      );
    }
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search