0

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]);
popoispoop
  • 19
  • 2
  • 1
    Remove `messages` from the dependency array – Phil Jul 26 '22 at 00:13
  • Since you're updating the `messages` state every time `fetchMessages` is called, and `messages` is inside the deps of your `useEffect`, you're creating an infinite loop. As @Phil stated, removing `messages` from your deps array will fix this. – GROVER. Jul 26 '22 at 00:16
  • define fetchMessages function in inside useEffect hook maybe that's help you – Jay Patel Jul 26 '22 at 11:59

0 Answers0