I'm getting the message in my console:
React Hook useEffect has a missing dependency: 'calculateTotalProductsPrice'. Either include it or remove the dependency array
The code is working but I dont know if is this is the proper way of implementing useEffect
Here I have a function that calculates the total price of my products and im calling it in my useEffect hook:
// Get all products the user added from my redux store
const allProductsAddedByUser = useSelector(state => state.createCampaign.campaign_products)
function calculateTotalProductsPrice() {
const productsArray = Object.values(allProductsAddedByUser)
const totalPrice = productsArray.reduce(function (prev, cur) {
return prev + cur.quantity * 125.0
}, 0)
return totalPrice
}
useEffect(() => {
calculateTotalProductsPrice()
}, [allProductsAddedByUser])
And in my html, I'm calling the function like this:
<span>€ {calculateTotalProductsPrice()}</span>
If I put the calculateTotalProductsPrice() function inside my useEffect hook, the warning from console is gone, but then I can't call my function like I was doing, I'm getting the error 'calculateTotalProductsPrice' is not defined. My function is now inside the useEffect hook, why cant I call her from outside?
// Get all products the user added from my redux store
const allProductsAddedByUser = useSelector(state => state.createCampaign.campaign_products)
useEffect(() => {
function calculateTotalProductsPrice() {
const productsArray = Object.values(allProductsAddedByUser)
const totalPrice = productsArray.reduce(function (prev, cur) {
return prev + cur.quantity * 125.0
}, 0)
return totalPrice
}
calculateTotalProductsPrice()
}, [allProductsAddedByUser])
// Call function from my html
<span>€ {calculateTotalProductsPrice()}</span>
// Error calculateTotalProductsPrice is not defined