-1

Why are two elements added instead of one?

My codesandbox

I apologize for such a short description, but I do not know what else to add

i like Cola
  • 277
  • 6
  • 15

1 Answers1

1

I resolved your issue... however please refer to the ask question section.

The issue is here

function reducer(state, action) {
  switch (action.type) {
    case "push":
      state.arr.push(action.payload);
      return { arr: state.arr };
    default:
  }
}

It should be like this, this is the typical reducer flow utilizing the spread operator.

   function reducer(state, action) {
      switch (action.type) {
        case "push":
          return {
            ...state,
            // spread the numbers 0, 1, 2, 3, && action.paylod appends the number/item to the array
            arr: [...state.arr, action.payload] // pass the action payload 
          }
        default:
      }
    }

Working demo

https://codesandbox.io/embed/useredux-duplicates-the-added-elements-forked-grznpc?fontsize=14&hidenavigation=1&theme=dark

BARNOWL
  • 3,326
  • 10
  • 44
  • 80
  • I understand I need to make the array meet the condition: state.arr !== returned state.arr. For example, this code is also working. const arr = Array.from(state.arr); arr.push(action.payload); return { arr }; – i like Cola Apr 23 '22 at 15:10