Whenever I set a variable using useState, the value is not immediately reflected. Here I have a useEffect that calls computePriceSummary();
useEffect(() => {
computePriceSummary();
}, []);
computePriceSummary calls three functions as shown:
const computePriceSummary = () => {
computeSubtotal();
computeTaxes();
computeTotal();
};
These functions set variables using useState:
const computeTaxes = () => {
let taxes = 0.05 * subtotal;
setTaxes(taxes);
};
const computeTotal = () => {
setTotal(taxes + subtotal);
};
const computeSubtotal = () => {
let subtotal = cart.products.reduce((acc, item) => {
return (acc += item.product.price * item.quantity);
}, 0);
setSubtotal(subtotal);
};
The values shown in the browser are:
Subtotal: $1200
Taxes: $0
Total: $0
The solution in Stackoverflow suggests using a useEffect to track the variables so I did:
useEffect(() => {
console.log("Use effect to immediately set variables");
}, [subtotal, taxes, total]);
The result is still the same.