Assign values of an array within a specific index of another array - React JS

Asked

Viewed 136 times

0

I am developing a simple private chat in Reactjs and Socket.io. However a problem has arisen to resolve the following situation.

First, I register users in the database through the Registry component. Then in the Userlist component all registered and stored users in the state of users , thus generating an array of objects containing all BD users.

Code snippet - Userlist.jsx

const [users, setUsers] = useState([]);

// Get All Users
    useEffect(() => {
        setLoading(true);
        axios.get(`${urlBase}/consult`)
            .then(resp => {
                setUsers(resp.data);
                setLoading(false);
            })
            .catch(err => {
                //console.log(err);
            })
    }, []);

At the same time using Socket.io, I send an Emit to the server stating the nickname of the user who just logged in. Hence, the server receives this data and returns an Emit passing the nickname sent along to the socket.id, to all connected users. This data is received on the client side of the application and added to usersOnline, array that stores users who are online.

Code snippet - Chat.jsx

const [userOnline, setUserOnline] = useState([]);

    useEffect(() => {
        socket.on('getOnline', data => {
            setUserOnline(data);
        });
    }, [userOnline]);

return of the first array - users

  0: {id_user: 68, first_name: "Fernanda", last_name: "Silva", email: "[email protected]", nickname: "fernanda", …}
  1: {id_user: 69, first_name: "Carlos", last_name: "Silva", email: "[email protected]", nickname: "carlos", …}
  2: {id_user: 70, first_name: "Pedro", last_name: "Perreira", email: "[email protected]", nickname: "pedrão", …}

return of the second array

nickname: "carlos"
socketId: "BwaRW_6zF5rCwRGcAAAC"

I need to pass to the primary array the second socketId in the respective nickname.

ex: in that case

1: {id_user: 69, first_name: "Carlos", last_name: "Silva", email: "[email protected]", nickname: "carlos", **socketId: "BwaRW_6zF5rCwRGcAAAC"**}

If anyone can help, I’d appreciate it!!

1 answer

1


In Javascript could do as follows:

users.find(user => user.nickname === response.nickname).socketId = response.socketId;

In the React, you can use the spread operator to create a new vector and not reference it with its state, it can be this way:

const newUsers = [...users];
const index = newUsers.findIndex(user => user.nickname === response.nickname);

if (index !== -1) {
   newUsers[index].socketId = response.socketId;    
   setUsers(newUsers);
}

Turns out, the method findIndex returns the first element of the vector that returns true in his callback. Like the nickname is unique, is a good option.

  • (Cannot set Property 'socketId' of Undefined) - It seems that it does not add the value because the field does not exist in the array...

  • In this case you can add a conditional structure. I edited the post :)

  • 1

    Thanks, you’re the man ;)

Browser other questions tagged

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