Search code examples
angularngrxngrx-store

Angular ngrx store reducer syntax problems


im working on angular project using ngrx store and i have the following reducer (old syntax) that works fine :

export function MyReducer(state = initState, action: Action): UserState {

  switch (action.type) {

    case UserActionsTypes.UPDATE_USER_SUCCESS:

      let updatedUser: USerDTO = (<USerActions>action).payload;
      let lstcurrentUsers = [...state.users];
      //update current user in list of users inside the store
      lstcurrentUsers = lstcurrentUsers.map(u => (u.id == updatedUser.id) ? updatedUser : u);

      return {
        ...state, dataState: USerStateEnum.LOADED, users: lstcurrentUsers, currentUSer: (<EnvelopeActions>action).payload
      }
      
      //...
      

now im working on a new syntax and this is my reducer :

export const MyReducer = createReducer(
    initState,

    on(UpdateUserActionSuccess, (state, { user }) => (
        {
            ...state, dataState: UserStateEnum.LOADED, currentUser: user, users: state.users.concat(user)
        }
    )),
    //...

my question is how i can add lines of code to manipulate state before returning it inside the on() method of my createReducer


Solution

  • Your reducer function is just a callback function, so you can do any work you'd like inside of it:

    export const MyReducer = createReducer(
        initState,
    
        on(UpdateUserActionSuccess, (state, { user }) => {
            const newState = { ...state };
    
            // do stuff to newState, then
    
            return {
                ...newState,
                dataState: UserStateEnum.LOADED,
                currentUser: user,
                users: state.users.concat(user)
            };
        }),
    

    Remember that state is immutable, so cannot be "modified". A reducer returns a brand new state object containing whichever changes you require.