I've been attempting to build a chatting service that re-renders each time a message is sent so that it can be in real-time.
I'm a bit new with hooks so I'm not exactly sure how I can get it to re-render only when a new message gets sent. I tried using the messages state but it would re-render like 10 times a second, and an empty array wouldn't update.
any suggestions would be really appreciated!!
EXTRA INFO: site is running on NextJS with a mongoDB as the database and axios to do fetching.
const [messages, setMessages] = useState(initialMessages);
// initialMessages is just a static server side prop passed to this component
const fetchMessages = async () => {
try {
const results = await axios.get("/api/fetchMessages"); // fetch from server
setMessages(results.data); // update state to fetched results
console.log("hello, world"); // just to view how many requests are being made
} catch (error) {
console.log(error);
}
};
useEffect(() => {
fetchMessages(); // calls function above
}, [messages]);