With this code on the component mount, there is a bug where priceToDisplay is first set as undefined, and it won't change state until some part of the component is not rerendered. If I remove that const from the dependencie array in useEffect, the correct value will be set.
const [isOnDiscount, setIsOnDiscount] = useState(
parseInt(product_data.discount_price && product_data.discount_price) !== 0
);
const [priceToDisplay, setPriceToDisplay] = useState(
isOnDiscount ? product_data.discount_price : product_data.price_of_product
);
useEffect(() => {
const isOnDiscountEffect = parseInt(product_data.discount_price) !== 0;
const priceToDisplayEffect = 0;
console.log(priceToDisplay);
if (isOnDiscountEffect) {
setPriceToDisplay(product_data.discount_price);
} else if (doesVariationAffectPrice()) {
// price of variation
} else {
setPriceToDisplay(product_data.price_of_product);
}
}, [priceToDisplay]);
Difficult to tell without knowing the whole component, but I assume that you are trying to do something like this:
export const Simple = ({product_data}) => {
const [priceToDisplay, setPriceToDisplay] = useState(null);
const isOnDiscount = parseInt(product_data.discount_price) !== 0;
useEffect(() => {
if (isOnDiscount) {
setPriceToDisplay(product_data.discount_price);
} else if (doesVariationAffectPrice()) {
// price of variation
} else {
setPriceToDisplay(product_data.price_of_product);
}
}, [isOnDiscount]);
return <div>
{priceToDisplay}
</div>
};
you dont need a state variable for isOnDiscountfor that.