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!!
(Cannot set Property 'socketId' of Undefined) - It seems that it does not add the value because the field does not exist in the array...
– Bruno Epíndola
In this case you can add a conditional structure. I edited the post :)
– Lucas Bittencourt
Thanks, you’re the man ;)
– Bruno Epíndola