title: Socket.io - Client listens to data changes from server automatically
body: <p>I'm trying to make something similar to a multiplayer game lobby using ReactJS, NodeJS and Socket.IO. Each time a new player/client connects to the socket, I want their name to be broadcasted on the frontend. </p>
  
  <p>So far I've been able to achieve this by having the frontend make a GET request to the backend every 3 seconds, which triggers a socket on the backend to send data obtained from a mongoDB database.</p>
  
  <p><strong>FRONTEND - lobby.js</strong></p>
  
  <pre><code>class Lobby extends Component {
  
  //When the component mounts, it calls grabNames function every 3 seconds.
  
    componentDidMount = () =&gt; {
      setInterval(this.grabNames, 3000);
    };
  
  //function makes a GET request that triggers the socket to emit a "joinedPlayers" message.
  
    grabNames = () =&gt; {
      axios.get(`${backend}/playerNames`).then(response =&gt; {
        console.log("Success");
      });
  
  //Listens for the "joinedPlayers" message to be emitted from the backend.
  //The joinedPlayers state is then referenced in the client-side markup.
  
      socket.on("joinedPlayers", data =&gt; {
        this.setState({ joinedPlayers: data.map(name =&gt; &lt;li&gt;{name}&lt;/li&gt;) });
      });
    };
  </code></pre>
  
  <p><strong>BACKEND - server.js</strong></p>
  
  <pre><code>//Function for connecting to the mongoDB database through Mongoose.
  
  function dbConnect() {
    mongoose
      .connect(database, { useNewUrlParser: true })
      .catch(error =&gt; console.error(error));
  }
  
  //Socket Connection
  
  io.on("connection", socket =&gt; {
    console.log("A connection to the socket has been established.");
  });
  
  //Router
  
  app.get("/playerNames", (req, res) =&gt; {
    dbConnect();
    Name.find((error, array) =&gt; {
      var playerNames = array.map(name =&gt; name.name);
      io.emit("joinedPlayers", playerNames);
      res.send("Player names emitted.");
    });
  });
  </code></pre>
  
  <p>Whilst this method is working for me, I can't help but think there is a better way for the frontend to listen for changes to the data from the server. </p>
  
  <p>For instance, is there a way the server can detect a change in my mongoDB database and update the client only when it detects this change... rather than having to periodically check every 3 seconds regardless of whether there is a change to the data or not?</p>
  
  <p>Any help would be greatly appreciated. Thank you!</p>