0

I have an object as follows:

{
  "1": {"stepNumber": 1, "isActive": false},
  "2": {"stepNumber": 2, "isActive": true},
  "3": {"stepNumber": 3, "isActive": true},
  "4": {"stepNumber": 4, "isActive": false}
}

In my reducer I'm sending through an action TOGGLE_ACTIVE_STEP which takes a payload of stepNumber Eg. 1 or 2 or 3...

Here's my reducer at the moment:

case TOGGLE_ACTIVE_STEP: {
  state.processSteps[action.data.stepNumber.toString()].isActive =
  !state.processSteps[action.data.stepNumber.toString()].isActive;

  console.log(JSON.stringify(state.processSteps));

  return {
    ...state,
    processSteps: state.processSteps,
  };
}

It's a pretty messy fix and I know that setting the state the way I do is not best practice since you should reassign parameters that way.

What is the best way to perform this same functionality?

2
  • What are you trying to achieve? Commented Oct 30, 2017 at 10:35
  • Immutability Helper. Commented Oct 30, 2017 at 10:36

1 Answer 1

2

Keep spreading props just like you are spreading state:

case TOGGLE_ACTIVE_STEP: {
  return {
    ...state,
    processSteps: {
      ...state.processSteps,
      [action.data.stepNumber]: {
        ...state.processSteps[action.data.stepNumber],
        isActive: !state.processSteps[action.data.stepNumber].isActive,
      }
    },
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! 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.