Z
Z
zlodiak2020-10-10 01:56:20
redux
zlodiak, 2020-10-10 01:56:20

How to push to a state property?

I wrote a form that sends its content to the global state. The reducer looks like this:

const messagesReducer = function messagesReducer(state = { messages: [] }, action) {
    switch(action.type) {
        case 'SET_MESSAGE': {
            // state = {
            //     ...state,
            //     messages: state.messages.push(action.payload),
            // };
            state.messages.push(action.payload);
            break;
        }
        default:
            return state;
    }
    return state;
}


It works without problems. The problems start when I try to push with the spread operator. To do this, in the code above, I remove comments from several lines of code. In this case, I get this error message:
Uncaught TypeError: state.messages.push is not a function


Please tell me how to fill the state with the spread-operator.

LIVE DEMO is here.

The state structure is like this:
5f80ea7472aff537735603.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-10-10
@zlodiak

case 'SET_MESSAGE':
  return {
    ...state,
    messages: [ ...state.messages, action.payload ],
  };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question