The code is working fine but when I come to the route for the first time (on intial render), the old message are there but when I type some new messages and send it. It doesn't appear on the screen. (the component doesn't re-render) Whereas, they have been storing in the database successfully and when I refresh the page and send the message they can be seen easily on the screen in the real time of both sender and receiver browser but again if I switch the route and come back again to the chat route then same problem. Tried to debug but wasn't able to. May be problem is related to the initial render and the way i am using useEffect. It would be really great if any one can help to figure out how this can be solved.
export default function Index({ auth, chats }) {
const { data, setData, post, processing, reset, errors } = useForm({
message: "",
});
const [allMessages, setAllMessages] = useState(messages);
useEffect(() => {
const channel = window.Echo.channel("chat");
channel.listen("SendMessageEvent", (newMessage) => {
setAllMessages((prevAllMessages) => [
...prevAllMessages,
newMessage.newMessage,
]);
});
return () => {
channel.unsubscribe();
};
}, []);
const submit = (e) => {
e.preventDefault();
post(route("messages.store"), { onSuccess: () => reset() });
};
}
// this are all the message
<div className="flex flex-col space-y-2">
{allMessages.map(message =>
<Message key={message.id} message={message} auth={auth}/>
)}
</div>
Please feel free to reach out for any further information......
Thanks for your time and consideration.