How do I tidy up this list of values from an array?

Asked

Viewed 32 times

0

I am chatting with Node.js and socket.io, I have an error in listing the values of an array, the array of users. I put a <ul></ul> with an id and nothing else. follow the prints below (the code on the left is the server and the one on the right is the client): this is the server:


io.on('connection', (socket) => {

    Msg.find().then(result => {
        socket.emit('output-messages', result)
    })

    /*User.find().then(result => {
        socket.emit('output-users', result)
    })*/

    socket.on('userConnected', (data) => {
        /*const userdb = new User({
            username: data.username
        });
        userdb.save().then(()=>{
            io.emit('displayUsers', data)
        }).catch(err =>{
            console.log("o erro foi: " + err)
        });*/

        io.emit('displayUsers', { users: users })


        users[socket.id] = data.username

        console.log(users)
    });

    socket.on('chat message', (data) => {
        const messagedb = new Msg({
            username: data.username,
            msgstring: data.msgstring
        });
        messagedb.save().then(()=>{
            io.emit('chat message', data)
        }).catch(err =>{
            console.log("o erro foi: " + err)
        });
        console.log(data)
    });


    socket.on('disconnect', function() {
        try{
            delete users[socket.id]
            io.emit('disconnection', {users: users})
        }
        catch(err){
            console.log(err)
        }
        console.log(users)
    });
});

and this is the client:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat da galera</title>

    <link 
        href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
        rel="stylesheet" 
        ntegrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" 
        crossorigin="anonymous"
    >
    <script 
        src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" 
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" 
        crossorigin="anonymous"
    ></script>

    <style>
        body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
  
        #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 15%; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
        #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
        #input:focus { outline: none; }
        #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }
  
        #messages { list-style-type: none; padding: 0; margin-left: 15%; }
        #messages > li { padding: 0.5rem 1rem; }
        #messages > li:nth-child(odd) { background: #efefef; }
        .namep{
            margin:0;
            padding: 0.5rem 1rem;
            color: rgb(10, 10, 10);
            background-color: rgb(180, 180, 180);
            font-size: 20px;
        }
        .namep2{
            margin:0;
            padding: 0.5rem 1rem;
            color: rgb(0, 0, 0);
            background-color: rgb(255, 255, 255);
            font-size: 25px;
        }
        #usersOnline{
            position: fixed;
            width: 15%;
            height: 100%;
            backdrop-filter: blur(10px);
            background: rgba(0, 0, 0, 0.15);
            bottom: 0;
            left: 0;
        }
        .usersH1{
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="usersOnline">
        <h1 class="usersH1" id="usersH1"></h1>
        <ul id="users"></ul>
    </div>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        var name = window.prompt("Your username:")

        if(name == null){
            alert("Please insert a valid name!");
            location.reload();
        };


        var socket = io();

        var messages = document.getElementById('messages');
        var usersUl = document.getElementById('users');
        var usersTitle = document.getElementById('usersH1');
        var form = document.getElementById('form');
        var input = document.getElementById('input');


        form.addEventListener('submit', function(e) {
            e.preventDefault();
            if  (input.value) {
                socket.emit('chat message', {
                    username: name,
                    msgstring: input.value
                });
                input.value = '';
            }
        });

        socket.emit('userConnected', {username: name});
        socket.emit('disconnection', {username: name});

        socket.on('output-messages', data => {
            console.log(data)
            if (data.length) {
                data.forEach(message => {
                    appendUsers(message.username)
                    appendMessages(message.msgstring)
                });
            };
        });

        /*socket.on('output-users', data => {
            console.log(data)
            if (data.length) {
                data.forEach(message => {
                    appendUsersTab(message.username)
                });
            };
        });*/

        socket.on("displayUsers", function(data){
            let county = Object.keys(data.users).length

            usersTitle.textContent = 'Users (' + [county + 1] + ')'; 
            //usersUl.textContent = '' + data.users + ''; 
            usersUl.textContent = Object.values(data.users)
        });

        socket.on('disconnection', function(data) {

            console.log(data.users)
        });

        socket.on('chat message', function(obj) {
            let nameP = document.createElement('p');
            nameP.className = "namep"
            nameP.textContent = obj.username + ":";
            
            let item = document.createElement('li');
            item.textContent = obj.msgstring

            messages.appendChild(nameP);
            messages.appendChild(item);
            window.scrollTo(0, document.body.scrollHeight);
        });

        function appendUsersTab(message) {
            const html = `<p>${message}:</p>`
            usersUl.innerHTML += html
        }

        function appendUsers(message) {
            const html = `<p class="namep">${message}:</p>`
            messages.innerHTML += html
        }
        

        function appendMessages(message) {
            const html = `<p style=" padding:0.5rem 1rem; ">${message}</p>`
            messages.innerHTML += html
        }
    </script>
</body>
</html>

When a new user arrives, only his name appears on <ul> when another user enters, and so it goes.

(the problem is in the part of users) telas dos clients conectados

  • 1

    I’m sorry, I put the code there

  • I didn’t look into the details, but <p> is not a valid tag within <ul>, may simply be that...

  • In fact, more likely the culprit is this line: usersUl.textContent = Object.values(data.users). Every time someone connects you totally overwrite the content of such UL

  • how can I fix this?

  • part of <p> within the <ul> I took it from the socket.io website, so the error might not be this, but in the same way, I’ll switch to div to see if it works.

  • this was not the mistake

  • In fact, to be honest, I know the mistake, but I can’t fix it. The error is: it only shows the Array when a user arrives, then it happened like this, the john entered, and only his name appeared when the peter entered, and only the name of the peter appeared when the josé entered, and the name of the josé did not appear because another person has to enter to update the Array.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.