Thursday, 1 June 2017

Display new entry to all users with Socket.io, Express and Handlebars

When a user adds an entry to the database, I am looking to reflect it on all open pages across users immediately. I am using Express, MongoDB and Handlebars with Socket.io. When User1 submits a new entry and it saves to MongoDB, User2 who is on the same page in a different browser, should instantly see the new entry on their page. I have tested the connection and am console logging when a new user is added. After playing around, I can't get it to reflect for all users without a manual refresh.

In server.js, I am saving the user:

// CREATE USER
app.post("/", function(req, res) {
  var randomNumbers = [];
  var min = Math.ceil(req.body.min);
  var max = Math.floor(req.body.max);

  function getRandomInt(min, max) {
    for (var i = 0; i < req.body.howMany; i++) {
      randomNumbers.push(Math.floor(Math.random() * (max - min)) + min);
    }
  };

  getRandomInt(min, max);

  // Create a new note and pass the req.body to the entry
  var newEntry = new Entry({
    name: req.body.name,
    min: req.body.min,
    max: req.body.max,
    howMany: req.body.howMany,
    numbers: randomNumbers
  });

  // And save the new note the db
  newEntry.save(function(error, data) {
    // Log any errors
    if (error) {
      console.log(error);
    }
    else {
      // Or send the document to the browser
      res.send(data);
    }
  });    
});

and also receiving the socket.io connection

io.on('connection', function(socket){
  console.log('a user connected');
});

Making the AJAX call in /public/app.js

// When you click the save entry button
$(document).on("click", "#saveEntry", function() {
  // Grab the id 
  // Run a POST request 
  $.ajax({
    method: "POST",
    url: "/",
    data: {
      // Value taken from name input
      name: $("#name").val(),
      // Value taken from inputs
      min: $("#min").val(),
      max: $("#max").val(),
      howMany: $("#howMany").val()
    }
  })

    // When that's done
    .done(function(data) {  
      // Log the response
      console.log(data);
    });
});

The socket is initiated in my main.handlebars file

<script>
    var socket = io();
</script>

index.handlebars displays the page

  
  <div class="item">
        <span class="name">  </span> <em>  :  </em>

        
        <ul class="children">
          
          <li>  </li>
          
        </ul>

       <div class="buttons">
        <button data-id= type="submit" class="delete button">REMOVE</button>
        <!-- Trigger/Open The Modal -->
        <button data-id= class="rename button">RENAME</button>

        <button data-id= class="updateNums button">MIN / MAX</button>
       </div>
  </div>
  

https://github.com/nathanchr/root-tree-app/tree/socket



via Nathan C.

No comments:

Post a Comment