2

I would need some help on Redux immutable array state. I am getting array of objects from actions and passing it to reducer. In my reducer file I am immutating the array and it gives me a new copy every time.

The problem that I am facing is it always gives me previous + new array (Which is correct) like keeps adding new array with new state and I need the last update array only. Because that I have to pass to react.

export default (state = {}, action) => {
    switch (action.type) {
        case EVT.LB_FOLLOWING_CHANGE:
            return [
                ...state,
                action.payload
            ];
            break;
        default:
            return state;
    }
};
2
  • depends some on what your action is doing. Based on what you've said, I think that what your action is returning (the action.payload) is what you want your state to become - is that right? If so, try changing return [ ...state, action.payload ] to return [ action.payload ]. Commented Jan 28, 2017 at 14:41
  • I should clarify that the above should work because what you are returning is the new state, and if your payload contains everything you want in the state, that's all you need to return. When you have ...state at the beginning of your return, you are first returning the current value of the state, and then appending the action.payload. That's why you are always getting your previous plus your new array. Commented Jan 28, 2017 at 15:52

2 Answers 2

1

You are getting the previous + new array because you are using the spread operator .... From the MDN documentation, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator

The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

In your case, using the spread operator before state appends all of the values inside the state array to the array that you are returning. To just return the value received in the action, you only need to return [action.payload].

You can refer the documentation link above to look at more examples of how to correctly use the spread syntax.

Sign up to request clarification or add additional context in comments.

Comments

0

Just do the following:

    case EVT.LB_FOLLOWING_CHANGE:
        return [action.payload];

Comments

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.