Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

75
Vistas
Reducer add item and update item in array of objects without mutation

Hello created reducer and wondering is this right pattern.

I am trying to:

  1. Add new item into array of objects ACTION_TYPE
  2. Update item in array of objects ACTION_TYPE_EDIT, this one actually should set charity prop and update item in array charities

Wondering if i am on right path, i don't want to mutate, so here is my code.

export const reducerCharities = (
  state: CharityReducerState,
  action: CharitiesAction
    | CharityEditAction
) => {
  switch (action.type) {
    case ACTION_TYPE_EDIT:
      return {
        ...state,
        charity: {
          ...state.charity,
          ...(action.charity || {}),
        },
        charities: [
          ...state.charities.map(item => item.id === action.charity?.id ? { ...item, ...action.charity } : item)
        ]
      }
    case ACTION_TYPE:
      return {
        ...state,
        charities: [
          ...state.charities || [],
          ...action.charities
        ]
      }
    default:
      return state
  }
}

So my question is will this part mutate state or is there better way to write this?

charities: [
          ...state.charities.map(item => item.id === action.charity?.id ? { ...item, ...action.charity } : item)
        ]

Is this right approach how to add new item into array

     {
        ...state,
        charities: [
          ...state.charities || [],
          ...action.charities
        ]
      }
7 months ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

The easiest (and since 2019 officially recommended) way of doing this would be using the official Redux Toolkit package and the createSlice method.

Within that, you can just mutate and don't have to care about manual immutable updates - the package takes over for you.

The code could look like

const charitiesSlice = ({
  name: 'charities',
  initialStae: myInitialState,
  reducers: {
    edit(state, action: PayloadAction<Charity>){
      const charity = state.charities.find(item => item.id === action.payload.id)
      if (charity) {
        Object.assign(charity, action.payload)
      }
      state.charity = action.payload
    }
  }
}
 
export const { edit } = charitiesSlice.actions
export const reducerCharities = charitiesSlice.reducer
7 months ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos