I’m building chat app using ReactJS, NestJS, Socket.io .
And it’s multi channel using rooms in socket.io
const [messages, setMessages] = useState({
ReactJS: [],
NestJS: [],
Typescript: [],
MySQL: [],
Neo4j: [],
Redis: [],
ELK: [],
Docker: [],
Kubernetes: [],
AWS: [],
SocketIO: [],
});
This is array with useState for pushing message.
Question
messages['ReactJS'].push(someMessage);
How useState push element to array inside object?
2
Answers
Given the state
Then the following is a way to update a specific room via a
roomKey
identifier nested in the state object. In React when you update state you must always return a new object reference, and this includes any nested state/properties that are being updated. array.prototype.push mutates the original array, it doesn’t create a new array reference for React purposes.An alternative to the array literal is to use array.prototype.concat, which does return a new array.
Note: This assumes your
roomKey
variable will reference one of the keys actually defined in your state. If you use an unspecified key thenmessages[unknownKey]
will be undefined. In this case, if you’ve truly dynamic keys, then you can provide a fallback value to spread into state.If you can install some additional utilities here are some other way to do it
Ramda
Immerjs