Adding data to state in Ngrx reducer function

Viewed 535

I am learning front-end and trying making an Angular app using NgRx for state management.

I have a table of Messages. I want to remove and add messages to store. I am able to remove rows using a reducer function as shown below.

function RemoveHandler(state: StoreMessages, action) {
    return {
        ...state,
        selections: state.selections.filter(messageId => messageId !== action.messageId),
        messages: state.messages.filter(item => item.messageId !== action.messageId),
        all: state.all.filter(item => item.messageId !== action.messageId)
    };
}

This works fine, but my logic for add message functionality is not working.

function AddHandler(state: StoreMessages, action) {
        return {
            ...state,
            messages: state.messages.push(action.newMessage),
            all: state.all.push(action.newMessage)
        };
    }

The problem is that pop method return length of array and hence length is assigned to 'messages' and 'all' properties of my state. How can I add new messages to my state. Any help is appreciated.

1 Answers

you don't need the array.push method in the reducer. the first code work, because you are filtering an array that is in the state. to add data to the state simply assign it like

function AddHandler(state: StoreMessages, action) {
    return {
        ...state,
        messages: action.newMessage,
        all: action.newMessage
    };
}

or if you are insert an array

function AddHandler(state: StoreMessages, action) {
    return {
        ...state,
        messages: [...action.newMessage],
        all: [...action.newMessage]
    };
}
Related