Home > Back-end >  cant update state even after copying it to a variable
cant update state even after copying it to a variable

Time:09-04

i have parent component SalesViewMain which has a useEffect function to call an async thunk redux function and sets these data to a useState.

useEffect(()=>{
    dispatch(getSalesAction(props.id)).unwrap().then(data=>{
        setSalesId(data.salesData.salesData[0].sales_id)
        setPayment(data.salesData.salesData[0].payment_type)
        setCashier(data.salesData.salesData[0].name)
        setDays(data.salesData.salesData[0].days)
        setDate(data.salesData.salesData[0].date)
        setProducts(data.salesData.products)
      })

},[])

then in that component i have a child component SalesViewProducts where i send the products data to the child component

<SalesViewProducts
        products={products}
        setProduct={setProducts}
        >
        </SalesViewProducts>

now in that child component im trying to call a function that will change the value of products state. ive done my research of copying the state first like [...props.products]. but even after copying it im unable to change the contents, met with the error cannot assign to read only property, why? ive already made a copy and i have no idea why this isnt working

const addProduct=(data)=>{

    var index;
    let copyArray = [...props.products]
    copyArray[0].quantity = 9
}

what should i do please help

CodePudding user response:

You need to create a copy of the object you want to update:

const addProduct=(data)=>{

    var index;
    let copyArray = [...props.products]
    copyArray[0] = {
        ...copyArray[0],
        quantity: 9
    }

    props.setProduct(copyArray)
}

CodePudding user response:

Are you sure this line isn't null?

data.salesData.products = null setProducts(data.salesData.products)

Try to:

useEffect(()=>{ 
   //get - full your products
   setProducts("your try")
},[])
        
console.log(products)

This always work for me to get to the problem

  • Related