based on a tutorial on youtube(https://www.youtube.com/watch?v=hiiaHyhhwBU&t=1195s) I am writing a chat application using react hooks in particular useReducer(). But I don't uderstand how in the switch case is returned an updated version of the state keeping just two elements and doesn't add a third element to the initState:
const initState = {
general: [
{from: 'ciro', msg: 'bella'},
{from: 'ciro', msg: 'bella'},
{from: 'ciro', msg: 'bella'}
],
private: [
{from: 'gennaro', msg: 'hello'},
{from: 'gennaro', msg: 'hello'},
{from: 'gennaro', msg: 'hello'}
]
}
const reducer = (state, action) => {
const { topic, from, msg } = action.payload;
switch(action.type) {
case 'RECEIVE_MESSAGE':
return {
...state,
[topic]: [
...state[topic],
{
from: from,
msg: msg
}
]
}
default:
return state;
}
}
I wonder how is [topic] able to update the message list corresponding to the topic as it is not directly linked to ...state? and how to the ...state is not just added a third element? I find this very confusing.
return {
...state,
[topic]: [
...state[topic],
{
from: from,
msg: msg
}
]
}
Thank you for your help