0

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

1 Answer 1

2

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;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I actually use combineReducers and have a separate reducer for the 'number' property of the state. The example above worked fine. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.