2

I'm having an issue where when I try to update an array in the store by using .push(newvalue). When I push the new value the state is updated from an array to being the value of the length of the array.

State before update: ['asd', 'sdf', 'wer']

State after: 4

action:

export function updateLocalCompliments(newCompliment) {
  return ({
    type: LOCAL_COMPLIMENT,
    payload: newCompliment
  })
}

reducer: (state.compliments is the actual array)

const INITIAL_STATE = {
  compliments: []
}

function compliments(state=INITIAL_STATE, action) {
      switch (action.type) {
        case LOCAL_COMPLIMENT:
          return (
            Object.assign({}, state, {
              compliments: state.compliments.push(action.payload)
            })
          )
        default:
          return state;
      }
    }
2
  • 1
    push does not return the mutated array but its updated length. You will need to handle this differently: developer.mozilla.org/de/docs/Web/JavaScript/Reference/… Commented Oct 4, 2017 at 18:10
  • 1
    push shouldn't be used with react-redux as it mutates the array Commented Oct 4, 2017 at 18:10

1 Answer 1

4

It is because the push method modifies the array it is called on and returns the new length. What you want is something like concat().

push: https://www.w3schools.com/jsref/jsref_push.asp

concat: https://www.w3schools.com/jsref/jsref_concat_array.asp

compliments: state.compliments.concat(action.payload)
Sign up to request clarification or add additional context in comments.

2 Comments

And here is some branchmark to compare what's the fastest array clone way: jsperf.com/new-array-vs-splice-vs-slice/31
That worked! Thanks for a clear explanation and resources for even more clarification.

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.