I want to update a simple html frontend with data coming in sporadically from the server via a websocket (I'm using socket.io). For each data, I want to create a <p> element with text inside it about the data, and append it as a child element inside <div>. Then I want the browser to automatically refresh the page to show it.
The backend is sending the data as it should when I logged it to the console. However, my frontend isn't rendering correctly. After data is sent, the browser doesn't refresh, thus not showing the <p> element. However, when I manually refresh it, the first <p> element would show and blink really fast. It does not show additional <p> elements as data is coming in.
Here is the frontend code in question:
<div id="names"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
let socket = io();
let nameDiv = document.getElementById('names');
socket.on('message', data => {
let newName = document.createElement('p');
newName.textContent = data.name;
nameDiv.appendChild(newName);
location.reload();
});
</script>
remove location.reload() from your code, then try again. You don't need to "refresh" in order for the DOM to reflect the changes you have made, the event loop will render the changes immediately.