'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
Solution 1:[1]
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;
}))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | brabade |