Home > Back-end >  useReducer duplicates the added elements
useReducer duplicates the added elements

Time:04-23

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

CodePudding user response:

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

  • Related