Wasteland
Wasteland

Reputation: 5389

react-native redux - reducer changing array elements

I have a state, part of which is an array called 'numbers'. One of the actions is to change the state in the following way: all the odd numbers should be changed to zero, all the even numbers should be kept. For example:

previous state
[9, 3, 2, 6, 8]

action
new state
[0, 0, 2, 6, 8]

action creator:

export const turnEven = () => {
  return {
    type: TURN_EVEN
  };
};

reducer:

case TURN_EVEN:
      return [...state, numbers: state.numbers.map(
        (i) => (i % 2 === 0 ? i : 0))];

This one produces an error: unexpected token, expected , ... and the 'return' line is being indicated as the location of the error. Please advise

Upvotes: 0

Views: 403

Answers (1)

Josep
Josep

Reputation: 13071

Looking at the code that you've shared:

case TURN_EVEN:
      return [...state, numbers: state.numbers.map(
        (i) => (i % 2 === 0 ? i : 0))];

It looks like the state of this reducer has different properties, one of them being numbers.

Maybe you wanted to do this instead:

case TURN_EVEN:
  return Object.assign(
    {},
    state,
    { numbers: state.numbers.map(i => (i % 2 === 0 ? i : 0)) }
  );

I haven't seen the rest of your reducer, so maybe I don't have enough context but I would encourage you to try to make a reducer for each one of the properties of the state, one of them numbers and then use combineReducers to combine them into one. Small functions are easier to deal with.

If you did that, then you could have a reducer like this one for numbers:

const initialState = [];
const numbersReducer = (state = initialState, action) => {
  swicth (action.type) {
    case TURN_EVEN:
      return state.map(i => (i % 2 === 0 ? i : 0));
    // Other action types here...
    default:
      return state;
  }
}

Upvotes: 2

Related Questions