0

I'm rendering an array(store cart items) on a screen and doing some modifications on selected objects. What I want to do is give kind of reset option to undo all the changes. Using map function instead of Flatlist as there'll be very less number of items. This is sort of question that is already asked but I couldn't find the same use case with the usage of React Hooks

export default function PreOrderRequest({route,navigation}) {

 const {item} = route.params
 const originalCart = item.data.cartItems //just making a copy.didn't help
 const [cartitems, setCartitems] = useState(item.data.cartItems)

 const addNote = async(index) =>{
  //will be adding some code with "await" later
  let cartItemsCopy = [...cartitems]
  cartItemsCopy[index].seller_notes='Out of stock' //original object didn't have this seller_notes key
  setCartitems(cartItemsCopy)
 }

 const resetChanges = ()=>{
  
  setCartitems(originalCart)

 }

 console.log({originalCart}) //this output changes after making changes to cartitems object

 return(
 )



}

Sample Object before modification

{
"category": "Rice", 
"customer_notes": "Chicken Ashanti", 
"item_quantity": 14, 
"type": "Chinese"
}

Sample Object after modification. Obtained by calling addNote function.

{
"category": "Rice", 
"customer_notes": "Chicken Ashanti", 
"item_quantity": 14, 
"type": "Chinese",
"seller_notes":"Out of stock" // this key,value has been added
}

I want to go back to the state before modification by addNote(). Am I doing some kind of wrong mutation here or referencing incorrectly?

SKR123
  • 233
  • 1
  • 12
  • 1
    Yes, you're modifying your state directly when you do `cartItemsCopy[index].seller_notes='Out of stock'`, use `.map()` insteed or create a new object and assign that to your desired `index` rather than updating the one in the array (see [here](https://stackoverflow.com/a/73747088/5648954) for more info). – Nick Parsons Sep 21 '22 at 13:07
  • 1
    You're a savior!! Thanks a lot! – SKR123 Sep 21 '22 at 13:16

0 Answers0