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

174
Visualizações
How to add a string in an array which is in an object which is in a state array

Now siizeVariant is a string Array and I want to add Strings to it with an onClick event. findIndex works fine. It's just the concat section. I guess it's wrong to use it there but I have no idea what to do else :/

const [selectedP, setSelectedP] = useState([
    {
      name: "Uomo - Valentino",
      productId: "H114",
      sizeVariants: []
    },
    {
      name: "Uomo - Valentino",
      productId: "H243",
      sizeVariants: []
    }
  ])

setSelectedP((prev as any[]) => {
      const index = selectedP.findIndex((sP: any) => sP.productId === productId);

      return [
        ...prev.slice(0, index),
        {
          ...prev[index],
          sizeVariants: prev.sizeVariants.concat(string),
        },
        ...prev.slice(index + 1),
      ];
    })
  }

This is the error I get: prev.sizeVariant is undefined

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

in place of using findIndex and slice method, use array.map for updating the array. And instead of using any type define a type and use it.

type product = {
    productId: number;
    sizeVariants: string[];
}
setSelecteP((prev: product[]) => prev.map(obj => {
    if (obj.productId === productId) {
        return {
            ...obj,
            sizeVariants: obj.sizeVariants.concat(newSizeVariant),
        };
    };
    return obj;
}))
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