Redux reducer, check if value exists in state array and update state

Viewed 23443

So I've got an array chosenIds[] which will essentially hold a list of ids (numbers). But I'm having trouble accessing the state in my reducer to check whether the ID I parsed to my action is in the array.

  const initialState = {
  'shouldReload': false,
  'chosenIds': [],
};

export default function filter(state = initialState, action) {
  switch (action.type) {


 case ADD_TYPE:
      console.log(state.chosenIds, "Returns undefined???!!!");

      // Check if NUMBER parsed is in state
      let i = state.chosenIds.indexOf(action.chosenId);

      //If in state then remove it
      if(i) {
        state.chosenIds.splice(i, 1);
        return {
          ...state.chosenIds,
          ...state.chosenIds
        }
      }
      // If number not in state then add it 
      else {
        state.chosenIds.push(action.chosenId)
        return { ...state.chosenIds, ...state.chosenIds }
      }

I'm not to sure what's going on...But when I log state.chosenIds, it returns undefined? It doesn't even return the initial empty array [] .

Basically what this function is suppose to do is check to see if the action.chosenId is in the state.chosenIds, If it is, then remove the action.chosenId value, if it's not, then add the action.chosenId to the state.

2 Answers

another aproach with a standalone function:

export default function reducer(state = initialState, action) {
    switch(action.type) {
        case ADD_TYPE:
             function upsert(array, item) {
    // (1)
    // make a copy of the existing array
    let comments = array.slice();
    const i = comments.findIndex(_item => _item._id === item._id);
    if (i > -1) {
      comments[i] = item;

      return comments;
    }
    // (2)
    else {
      // make a copy of the existing array
      let comments = array.slice();
      comments.push(item);

      return comments;
    }
  }

            return {
     ...state,
    comments: upsert(state.comments, action.payload),
            };
        default:
            return state;
    }    
}
Related