Francky Vincent
Francky Vincent

Reputation: 573

Redux reducer weird behavior?

Hey guys i wonder why my state is getting undefined after I process through this :

Just want to decrease the like property from 1 do you guys see issues in my nested processing ?

 case "UNLIKE_COMMENT":
      const unLikeIndex = getKeyIndex(
        state.list[action.index],
        action.commentId
      );

      return updateObject(state, {
        isFetching: false,
        list: {
          ...state.list,
          [action.index]: updateValue(unLikeIndex, state.list[action.index], {
            [unLikeIndex]: {
              ...state.list[action.index][unLikeIndex],
              like: state.list[action.index][unLikeIndex].like - 1,
            },
          }),
        },
      });


export const updateObject = (oldObject, newValues) =>
  Object.assign({}, oldObject, newValues);


export const updateValue = (index, state, value) =>
  state.map((item, i) => {
    i === index ? value : item;
  });

// Tested and works
export const getKeyIndex = (array, keyToFind) => {
  let ret = -1;
  array.forEach(({ key }, index) => {
    if (key === keyToFind) ret = index;
  });

  return ret;
};

Before / After processing

Before / After processing

Upvotes: 0

Views: 74

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42170

Honestly I am finding your code incredibly hard to read and there may be more errors than just this one. But for sure your updateValue function is mapping the array to undefined.

export const updateValue = (index, state, value) =>
  state.map((item, i) => {
    i === index ? value : item;
  });

The problem is that you put your map callback inside of curly braces {} without a return statement. map replaces every element with the returned value, so it replaces every element of the array with undefined.

You can either add the word return

updateValue = (index, state, value) =>
  state.map((item, i) => {
    return i === index ? value : item;
  });

Or write it inline without the curly braces

updateValue = (index, state, value) =>
  state.map(
    (item, i) => i === index ? value : item
  );

Upvotes: 1

Related Questions