Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
How to update Nested Array with useReducer?

I have these:

export type DataItemChild = {
  id: number;
  title:string;
  checked?: boolean;
};

Note that subItems can be undefined here:

export type DataItems = {
  id: number;
  title:string;
  subItems?: Array<DataItemChild>;
  checked?: boolean;
};

export const initalState: StateType = {
  items: [],
  date: new Date(),
};

So far I have figured out how to update the array on top level object like:

  case ActionKind.Checked:
    newArrayChecked = state.items.map((item) => ({
      ...item,
      checked: item.id === payload.id ? true : item.checked,
    }));
    return {
      ...state,
      items: newArrayChecked,
    };

I can not figure out how to update the subItems? i have this (stripped down)

export const reducer = (state: StateType, action: Action) => {
  const { type, payload } = action;
  let newArrayChildCheck: Array<DataItemChild> = []
  switch (type) {

    case ActionKind.UnCheckedSub:
      newArrayChildCheck = state.items.map((item) => ({
        ...item.subItems?.map((sub, index) => ({
          checked:  sub.id === payload.subItems?[index].id ? true: sub.checked
        })),
      }));
      return {
        ...state,
        items.subItems: newArrayChildCheck,
      };

    default:
      return state;
  }
};

But this gives me a typscript error saying that my newArrayChildCheck does not support undefined. Full error:

Type '{ [x: number]: { checked: boolean | undefined; }; length?: number | undefined; toString?: (() => string) | undefined; toLocaleString?: (() => string) | undefined; pop?: (() => { checked: boolean | undefined; } | undefined) | undefined; ... 29 more ...; [Symbol.unscopables]?: (() => { ...; }) | undefined; }[]' is not assignable to type 'DataItemChild[]'. Type '{ [x: number]: { checked: boolean | undefined; }; length?: number | undefined; toString?: (() => string) | undefined; toLocaleString?: (() => string) | undefined; pop?: (() =

EDIT:

after @Kelvin Schoofs answer I realized I am sending in an entire object which has its subitems. the payload is of a type DataItems

I modified my attempt according to @Kelvin Schoofs suggestion with a little twist:

  newArrayChildCheck = state.items.map((item) => ({
    ...item,
    subItems: item.subItems?.map((sub, index) => ({
        ...sub,
        checked: sub.id === payload.subItems[index].id ? true : sub.checked
    })),

Not the [index]

But I am getting

object is possible undefined

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It seems like you're spreading your new object wrong. Your .map((item) => ...) returns an object, but in it you spread a (potential) array, which would only fill in numeric (well, stringified versions) keys. You probably meant to copy over the original fields from item such as id and title, and assign the mapped subItems result to the subItems field. Idem for the object you create in your subItems?.map. Something like this is type-correct:

newArrayChildCheck = state.items.map((item) => ({
    ...item,
    subItems: item.subItems?.map((sub) => ({
        ...sub,
        checked: sub.id === payload.id ? true : sub.checked
    })),
}));

That's if you want an altered version of your DataItems array. If you actually want to return every DataItemChild with the checked version altered, you can use flatMap like this:

newArrayChildCheck = state.items.flatMap((item) => 
    item.subItems?.map((sub) => ({
        ...sub,
        checked: sub.id === payload.id ? true : sub.checked
    })),
);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda