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
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
it was not returning true. i had to make it
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.
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: