-1

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

  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"**DO NOT post images of code, data, error messages, etc.** - copy or type the text into the question. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text."_ – Andreas Feb 12 '22 at 11:17
  • You've indicated that `prev` is an array, but are trying to access `sizeVariants` on it. `(prev as any[]) => {... prev.sizeVariants`. (this is clearly stated in the error image) – pilchard Feb 12 '22 at 11:26
  • Ah my bad, but now I get `prev.sizeVariant is undefined` @pilchard – cocoscocos Feb 12 '22 at 11:30
  • You need to access `sizeVariants` on the relevant object using the index `prev[index].sizeVariants.concat(string)` – pilchard Feb 12 '22 at 11:31
  • That's it, thank you! @pilchard – cocoscocos Feb 12 '22 at 11:33
  • No worries, glad it's working. – pilchard Feb 12 '22 at 11:34

1 Answers1

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;
}))
brabade
  • 36
  • 2