0
votes

Trying to update an array of objects via ngrx-reducer I found some examples in the web (e.g. https://blog.strongbrew.io/Redux-best-practices/)

Some of them try to perform state.map, but I get an error "property 'map' does not exist on type 'state'".

In an array of objects, I would like to update the property languageStrg of one of the objects. Here is my code:

export function langsReducer(state = initialState, action: LangsActions): State {
    switch (action.type) {
        case ActionTypes.SETLANG: {
            return state.map(obj =>
                obj.languagePurpose === action.payload.languagePurpose ?
                {...state, languageStrg: action.payload.languageStrg} :
                obj);
            }
}

How could I rewrite the code so that the update works?

2
Could you please show the definition of initialState?Vitalii Ilchenko
const initialState: State = { languages : [ {languagePurpose: 'frontend', languageStrg: 'de'}, {languagePurpose: 'backend', languageStrg: 'de'}, ], };JJJanezic

2 Answers

2
votes

In your case it will be

export function langsReducer(state = initialState, action: LangsActions): State {
    switch (action.type) {
        case ActionTypes.SETLANG: {
            return {
                ...state,
                languages: state.languages.map(obj =>
                    obj.languagePurpose === action.payload.languagePurpose
                        ? {...obj, languageStrg: action.payload.languageStrg}
                        : obj
                    )
            };
        }
        default:
            return state;
    }
}
0
votes

your reducer should return the state in the default case in the switch case.

your initial state should look like this if you want to use arr of objects

const initialState = {
    arr = []
}