I am building a chat app. I want the client to always see the latest message when he opens the screen. My issue is that it does not work properly during the initial render. If I send a message and when the state changes it works perfectly. I can’t figure out how this useEffect works. Please help me out. Even if I refresh the page it wont work how it supposed to work.
//socket to listen to incoming messages. When a new message arrives it is pushed into redux store
useListenToMessages()
//state to manage the message to send
const [message, setMessage] = useState('');
//this is where iam getting the previous messages from the database. The messages are stored in the redux store from the hook itself. Its an axios call.
const { loading } = useGetMessages();
// last message div refference
const recentMessageRef = useRef<HTMLDivElement | null>(null);
//retrieving the saved messages from the store.
const messages = role == 'student' ?
useAppSelector(state => state.studentClassroom.classroom?.classroom_messages || []) :
useAppSelector(state => state.teacherClassroom.classroom?.classroom_messages || []);
//useEffect hook to direct the view to latest message. whenever the state in redux changes it works. but not workin during the initial render.
useEffect(() => {
if ( recentMessageRef.current) {
console.log('rolling to down...')
recentMessageRef.current.scrollIntoView({behavior:'smooth'})
}
}, [messages])