Oops, my friends, I have this "problem" when using setState, as setState is not asynchronous I can't use it the way I want. I set the value and when calling the function to send back the value returns with "delay". How do I resolve this?
const [quantityProduct, setQuantityProduct] = useState<number>(0);
function addQuantity() {
var soma = Number(quantityProduct) + 1;
setQuantityProduct(soma);
sendProduct()
}
function sendProduct() {
console.log(quantityProduct)
}
The issue is that the following two lines are asynchronous. What you experience is the second line gets executed before completing the first one.
setQuantityProduct(soma);
sendProduct();
You meant to call sendProduct when the quantityProduct gets updated. You should be using useEffect hook with quantityProduct in the dependency array.
Try like below.
const [quantityProduct, setQuantityProduct] = useState<number>(0);
function addQuantity() {
var soma = Number(quantityProduct) + 1;
setQuantityProduct(soma);
}
function sendProduct() {
console.log(quantityProduct);
}
useEffect(() => {
sendProduct();
}, [quantityProduct]);
2nd way: calling the API inside setState callback
function addQuantity() {
setQuantityProduct((prevQuantity) => {
var newQuantity = Number(prevQuantity) + 1;
sendProduct(newQuantity);
return newQuantity;
});
}
"setState is not asynchronous"
This isn't true. The documentation is clear on this:
React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.
You need to use the useEffect hook to watch for changes in state (passing in the state you want to watch in a dependency array), and then perform an operation based on that change.
const [quantityProduct, setQuantityProduct] = useState(0);
function addQuantity() {
const soma = Number(quantityProduct) + 1;
setQuantityProduct(soma);
}
function sendProduct() {
console.log(quantityProduct);
}
useEffect(() => {
sendProduct();
}, [quantityProduct]);