In a React app, I got a state variable that's set to 0 at first.
const [amount, setAmount] = useState(0)
The functionality i'm looking for is to add/remover product in a redux store.
So if a user presses a "+" button, it will check if amount is now bigger than 0,
and if so it'll dispatch an action to the store.
But what I'm getting is that only after the second "+" press, when the value of amount is already 2,
the action is actually dispatched.
This is the code :
const handleAmount = action => {
if (action === 'plus') {
setAmount(currAmount => currAmount + 1)
updateStore()
}
}
const updateStore = () => {
if (amount >= 1) {
dispatch(addToCart(product))
}
}
What am I missing?
amountin redux also?setStateapplies changes only in the next render. Redux and useReducer on the other hand give you the current state once they have changed.