0

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

TommasoVasari
  • 29
  • 1
  • 7
  • 1
    Does this answer your question? [Square Brackets Javascript Object Key](https://stackoverflow.com/questions/32515598/square-brackets-javascript-object-key) – M0nst3R Jul 13 '20 at 17:43

1 Answers1

1

You can refer to this documentation:

Basically when you ask:

how to the ...state is not just added a third element?

It's because:

The Rest/Spread Properties for ECMAScript proposal (ES2018) added spread properties to object literals. It copies own enumerable properties from a provided object onto a new object. Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

If objects have a property with the same name, then the right-most object property overwrites the previous one.

Regarding:

I wonder how is [topic] able to update the message list corresponding to the topic?

I think this: Square Brackets Javascript Object Key is very clear, if it is not please don't hesitate to ask.

SGali
  • 70
  • 1
  • 1
  • 6
  • 1
    The first half of your answer really answered my question on the second half i think i didn't express myself really well as i was wondering how [topic] knows that needs to update a property of state as it is not directly linked to it, but you answered that on the first half. Very helpful, thank you! – TommasoVasari Jul 13 '20 at 18:24