I'm developing a chat application and so far i'm polling my server for messages every two seconds. To make the chat more instant i'd like to implement long polling. I'm trying to implement this JS.info Guide for it but i keep not hitting the goal i intend to hit. Can anyone point this out for my case?
I have a custom hook for this in react which is basic polling for now.
FYI: I'm a beginner and wont use WS or Socket.io now. It's too much for me at this point.
Thanks in advance!
export default function useGetChatMessages(_id) {
const [chatMessages, setChatMessages] = React.useState([]);
React.useEffect(() => {
const interval = setInterval(() => {
getChatMessages(_id).then(fetchedChatMessages => {
setChatMessages(fetchedChatMessages);
});
}, 2000);
return () => clearInterval(interval);
}, [_id]);
return chatMessages;
}
This is my server function with express. I guess it should be implemented here rather than in my hook
router.get('/:id/messages', async (request, response) => {
try {
const chat = await Chat.findById(request.params.id);
response.json(chat.messages);
} catch (error) {
console.log(error);
response.status(500).json({ message: error.message });
}
});