I'm working on a React app with websocket. In this app there is a socket event listener which returns 3 types: add
, change
, and remove
. Certain state update operations will be performed based on the type received.
Do I properly mutate the users
state? I'm not sure whether it follows the principle of React regarding updating states.
ws.on("connect", () => {
console.log("connected");
ws.emit("load");
});
ws.on("feed", response => {
const prev = response.old_val;
const next = response.new_val;
const type = response.type;
setUsers(users => {
let currentUser = [...users];
let index;
switch (type) {
case "add":
return [...users, next];
case "change":
index = users.findIndex(u => u.id === next.id);
currentUser[index].name = next.name;
return currentUser;
case "remove":
index = users.findIndex(u => u.id === prev.id);
currentUser.splice(index, 1);
return currentUser;
default:
return currentUser;
}
});
});