0

I am currently having an issue adding/reducing to an array via redux. Just to make sure my redux state works, i hard coded values in and it triggers every time i press a button.

Code that works:

import * as actionType from '../actions/ActionType';

const counterReducer = (state = [], action) => {
  let newState = [];
  switch (action.type) {
    case actionType.ADD_FILTER:
      if (!state.includes(action.payload)) {
        return newState = ['test'];
      }
      return newState = ['test'];
    default:
      return state;
  }
};

export default counterReducer;

Code that doesnt trigger a rerender:

import * as actionType from '../actions/ActionType';

const counterReducer = (state = [], action) => {
  let newState = [];
  switch (action.type) {
    case actionType.ADD_FILTER:
      if (!state.includes(action.payload)) {
        const current = state;
        current.push(action.payload);
        return newState = current;
      }
      return newState = state;
    default:
      return state;
  }
};

export default counterReducer;

The redux store however updates? Help?

3
  • What do you get when you do console.log(action.payload)? I think you must be getting undefined Commented Nov 2, 2018 at 11:25
  • @Think-Twice i get the value of the button. So for example, if button is called 'Arriving Today', action.payload would be a string 'Arriving Today' Commented Nov 2, 2018 at 11:26
  • this, I think should work. Can you make a quick stakcblitz version of this and paste the link here? Commented Nov 2, 2018 at 11:31

1 Answer 1

1

The code that doesn't work, the reason for that is you are mutating your state(using push method on an array which has reference to the old state), which redux will not register as a change because you are again passing the reference of the old state. Read on cloning arrays and slice method.

const current =state.slice();
current.push(action.payload)
return current

Now that you have a proper clone, return that array. That would trigger re-render.

Also, the first case works because you are always creating a new array and its reference.

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

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.