Search code examples
javascriptarraysangularreduxngrx

Angular 2 ngrx : how to update an array which is embedded in one the the items of my state array?


In my reducer, I would like to add an element which is in an array like this:

The JSON structure (received with http services):

{
 "id": "09fabf9a-e532-4d2a-87cc-bd949a0a437f",
 "title": 'my title',
 "itemId": "6d442772-d414-46b1-8aab-a105d2bc3b38",
 "createdOn": "2017-01-12T10:12:22.987Z",
 **"replays": []**
}

So I would like to add (and why not update) this replays array, which is in the reviews array.

REVIEWS ARRAY :

[review1,review2,review3...review(n)]

I already have a reducer for managing the reviews, but how would I do it with replays the redux way? Thanks

EDIT 1: REDUCER CODE

xport const Reviews: ActionReducer<Array<Review>> = (state: any[] = [], action: Action) => {
    switch (action.type) {
        case GET_REVIEWS:
            return action.payload;
        case ADD_REVIEW:
            return [...state, action.payload];
        case UPDATE_REVIEW:
            let index = state.map(review => review.id).indexOf(action.payload.id);
            return [
                ...state.slice(0, index),
                Object.assign({}, state[index], action.payload),
                ...state.slice(index + 1)
            ];
        case DELETE_REVIEW:
            return state.filter(item => {
                return item.id !== action.payload;
            });
        case ADD_REPLAY:
           return 'HERE I'AM STUCK !'
        default:
            return state;
    }
};

Solution

  • Assuming your action for the ADD_REPLAY action is an object with the review's ID plus the Replay to add. In order to not mutate the objects (replay and review) you have to replace them.

    case ADD_REPLAY:
        let index = state.map(review => review.id).indexOf(action.payload.id);
        return [
            ...state.slice(0, index),
            Object.assign({}, state[index], {
                replays: [...state[index].replays, action.payload.replay]
            }),
            ...state.slice(index + 1)
        ];
    

    There's a great free video explaining how to avoid array mutations on egghead.