Search code examples
react-reduxreact-state-management

meaning of state in Delete items from state array - useReducer


Hi all i am new to react hooks.Please explain what is the meaning of state.items in DELETE_ITEM case.Is this a single object if yes then how.

let initialState = {
  items: [
   {
       name: 'A',
       age: 23
   },
    {
       name: 'B',
       age: 20
      },
      {
      name: 'C',
      age: 29
      }
  ]
}
const userReducer = (state = initialState, action) => {
   switch(action.type){
 case DELETE_ITEM:
return {
...state,
items: state.items.filter((item, index) => index !== action.payload)
}
   }
}

Solution

  • state.items is the items object from your state. It starts off as described in initialState. That's the initial value. Then, in the reducer, subsequent actions such as DELETE_ITEM might alter that value.

    The current state of that items value is what you have in state.items. Hence, the name. It's not a single object, it's the entire items array.