0

I have the following state object in redux:

console.log({
  jobOffers: {
    filters: {
      employments: [],
      careerLevels: [],
      jobTypeProfiles: [],
      cities: [],
      countries: [],
      searchTerm: '',
      currentPage: 1,
      pageSize: 5
    }
  }
});

I want to set the array employments new.

That's my redux reducer:

export const reducer = (state = initialStateData, action) => {
  switch (action.type) {
    case Action.SET_ARR_FILTER:
      {
        const newNestedState = {

          ...state[action.key],
          [action.key]: action.value,
        };
        return { ...state,
          [action.key]: newNestedState
        };
      }
    default:
      return state;
  }
};

The action:

export const SET_ARR_FILTER = 'SET_ARR_FILTER';
export const setEmployment = employment => ({
  type: SET_ARR_FILTER,
  key: 'employments',
  value: employment,
});

But my object looks like this after the reducer has been called:

console.log({

  employments: {
    employments: ['HelloWorld']
  },

})

What is wrong here ?

Shivam
  • 3,514
  • 2
  • 13
  • 27
Gutelaunetyp
  • 2,144
  • 4
  • 15
  • 40

3 Answers3

0

You're a level too deep (or not deep enough, depending on how you see it).

You need something like:


case Action.SET_ARR_FILTER:
      {
        const { filters } = state
        return { ...state,
          filters: {
            ...filters,
            [action.key]: action.value 
          }
        };
      }

Mark Michon
  • 725
  • 5
  • 7
  • If your state has more than just `filters` in it, you might want to consider breaking it up into multiple reducers. Also would be useful to see what employments before and after looks like, along with what employment looks like in that scenario. Either way, the concept is the same: return spreaded state, override target key, spread substate, override target key, etc. – Mark Michon Oct 10 '19 at 20:44
0

Similar to Mark's answer, all one line if you like.

export const reducer = (state = initialStateData, action) => {
  switch (action.type) {
    case Action.SET_ARR_FILTER:
      return {
          ...state,
          filter: {
                  ...state.filter,
                  [action.key]: action.value
              }
      }
    default:
      return state;
  }
};

xandermonkey
  • 4,054
  • 2
  • 31
  • 53
0

Finally got it myself. Answer is:

case Action.SET_ARR_FILTER:
  {
    return {
      ...state,
      jobOffers: {
        ...state.jobOffers,
        filters: { ...state.jobOffers.filters,
          [action.key]: action.value
        },
      },
    };
  }
Gutelaunetyp
  • 2,144
  • 4
  • 15
  • 40