title: React project- chatting app. Need advice on setting interval
body: <p>below is my main code for my project, which is a simple open chatting room.
  This is a chatting client basically, which can only get chatting logs and post chats.
  To log in, I request for an authorization key to the server and use that key to start chatting.</p>
  
  <p>The thing that I want to do is to get the chatting logs from the server every 3 seconds.
  So, after it retrieves chats every 3 seconds, the page should refresh with new chats. 
  However, this seems not to be working well for me. </p>
  
  <p>If there is a good React pro who can solve this problem for me, please do. </p>
  
  <pre><code>import React from 'react';
  import { withRouter } from 'react-router-dom';
  
  import './Chat.css';
  
  import InfoBar from '../InfoBar/InfoBar';
  import Input from '../Input/Input';
  import Messages from '../Messages/Messages';
  
  const API_ENDPOINT = 'https://snu-web-random-chat.herokuapp.com';
  let INTERVAL_ID;
  
  const Chat = ({ token, setToken }) =&gt; {
      const [ name, setName ] = React.useState('');
      const [ message, setMessage ] = React.useState('');
      const [ messages, setMessages ] = React.useState([]);
      const [ lastEl, setLastEl ] = React.useState({});
  
      React.useEffect(() =&gt; {
          if (localStorage.getItem('username')) {
              setName(localStorage.getItem('username'));
          }
  
          window.addEventListener('scroll', listenToScroll, true);
  
          fetchData();
  
          INTERVAL_ID = setInterval(() =&gt; {
              fetchData();
          }, 3000);
  
          return () =&gt; {
              window.removeEventListener('scroll', listenToScroll);
              clearInterval(INTERVAL_ID);
          };
      }, []);
  
      const fetchData = () =&gt; {
          fetch(`${API_ENDPOINT}/chats?createdAtFrom=${lastEl.createdAt || ''}`)
              .then((res) =&gt; res.json())
              .then((msgs) =&gt; {
                  const updatedMsgs = messages.concat(msgs);
  
                  setLastEl(msgs[msgs.length - 1]);
                  setMessages(updatedMsgs);
              });
      };
  
      const listenToScroll = (e) =&gt; {
          const div = document.getElementById('messagesContainer');
          // console.log(window.scrollY);
          // const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  
          // const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  
          // const scrolled = winScroll / height;
      };
  
      const onLogin = (e) =&gt; {
          e.preventDefault();
  
          fetch(`${API_ENDPOINT}/login`, {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/x-www-form-urlencoded'
              },
              body: `name=${name}`
          })
              .then((response) =&gt; response.json())
              .then(({ key }) =&gt; {
                  if (key) {
                      setToken(true);
                      localStorage.setItem('__key', key);
                      localStorage.setItem('username', name);
                  }
              })
              .catch((err) =&gt; console.error(err));
      };
  
      const sendMessage = (e) =&gt; {
          e.preventDefault();
  
          if (message) {
              fetch(`${API_ENDPOINT}/chats`, {
                  method: 'POST',
                  headers: {
                      'Content-Type': 'application/x-www-form-urlencoded',
                      Authorization: `Key ${localStorage.getItem('__key')}`
                  },
                  body: `message=${message}`
              })
                  .then((response) =&gt; response.json())
                  .then((res) =&gt; {
                      const obj = {
                          createdAt: res.createdAt,
                          message: res.message,
                          userName: res.user.name,
                          _id: res.user._id
                      };
                      setMessages([ ...messages, obj ]);
                  })
                  .catch((err) =&gt; console.error(err));
  
              setMessage('');
          }
      };
  
      const logout = () =&gt; {
          localStorage.removeItem('__key');
          localStorage.removeItem('username');
          setToken(false);
      };
  
      const loadMessages = () =&gt; {
          fetchData();
          clearInterval(INTERVAL_ID);
      };
  
      return (
          &lt;div className="outerContainer"&gt;
              &lt;div className="innerContainer"&gt;
                  &lt;InfoBar
                      name={name}
                      token={token}
                      handleInput={(e) =&gt; setName(e.target.value)}
                      handleLogin={onLogin}
                      handleLogout={logout}
                  /&gt;
                  &lt;Messages messages={messages} name={name} lastEl={lastEl} loadMore={loadMessages} /&gt;
                  {token &amp;&amp; &lt;Input message={message} setMessage={setMessage} sendMessage={sendMessage} /&gt;}
              &lt;/div&gt;
          &lt;/div&gt;
      );
  };
  
  export default withRouter(Chat);
  </code></pre>