I have an object, who has an array in its props. I am trying to change an item's value inside this array (inside the object). This object is coming from Redux.
const [product, setProduct] = useState(useSelector(selectProducts).find((item) => item.id === id))
console.log(product)
// { name: "",
// imageUrls: ["https://blabla","https://blabla2","","",""],
// quantity: "" }
I tried
setProduct((prevState) => {
let copy = {...prevState}
copy.imageUrls[i] = ""
return copy
})
And then the error comes: Uncaught TypeError: Cannot assign to read only property '1' of object '[object Array]'
I also tried adding
Object.defineProperties(product, {imageUrls: {configurable: true, writable: true}})
Then, again error, object is not redefinable.
Can you help?
CodePudding user response:
const selectProducts = [
{name:"",imageUrls:["https://blabla","https://blabla2","","",""], quantity:""},
{name:"",imageUrls:["https://blabla3","https://blabla4","","",""], quantity:""}
]
const persistedProducts = selectProducts.map((product)=>{
const {imageUrls, ...productWithoutImageUrls } = product;
return {
...productWithoutImageUrls,
imageUrls: imageUrls.map((imageUrl)=>"")
}
})
console.log(persistedProducts)
CodePudding user response:
Would you like to try with this?
const productState = useSelector(selectProducts);
const [product, setProduct] = useState({ ...productState });
Then you can use setProduct wherever you want to update product.