I am burning out here so I may be missing something, why is it not following the parameters?
const addItem = ()=>{ const newValue = setCounter(counter 1);
if (newValue < {stock}){
setCounter(newValue)
} else if(newValue > {stock}) {
alert("Stock is full");
setCounter({stock})
}
}
const quitItem =()=>{
const newValue = setCounter(counter -1)
if( newValue < initial){
setCounter(initial)
}
}
CodePudding user response:
Why are you using setCounter to return a value, it is a setter so its function is only to set the counter to the new value
const quitItem =()=>{
setCounter(counter -1)
if( counter < initial){
setCounter(initial)
}
CodePudding user response:
Whenever you call setCounter, you are actually updating its value in React state. So in the first line inside addItem
you have already updated the value of the counter.
The next thing is that you inside addItem
is comparing newValue
to an object with the variable stock
. You should probably compare the value against the value of stock
, not an object containing stock
.
Try this:
const addItem = () => {
const newValue = counter 1;
if (newValue < stock){
setCounter(newValue)
} else if (newValue > stock) {
alert("Stock is full");
setCounter(stock)
}
}
const quitItem = () => {
const newValue = counter -1
if (newValue < initial){
setCounter(initial)
}
}