Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda