Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!