My app has a cart feature in which the quantity of the items increases every time the user hits the add button. I have the codesandbox linked below.
The functionality works as required when a meal is added for the first time to the cart. When I add hit add the second time on the same meal, the increment is doubled.
Increment Amount: 3
quantity = 0;
First Add:
quantity = 3;
Second Add:
quantity = 9;
Third Add:
quantity = 15;
I know that this is happening because of StrictMode. Due to StrictMode the setState method is being executed twice and the quantity increment is happening twice.
Could someone suggest some way to fix my code without removing StrictMode?
When you call setOrderDetails with a function parameter, you should not use orderDetails in that function. Instead you should use prev.
You are also mutating the orders inside the orderDetail (line 28) which will cause problems. Instead you should make a new order object with an updated quantity.
See here https://codesandbox.io/s/multiple-state-exec-forked-klc81n for an example.