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

175
Vistas
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 Respuestas
Responde la pregunta

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 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