Mel
Mel

Reputation: 3

Rerendering issue in React hooks

I want to re render my browser every time cart is updated to update the calculatedPrice state of a cart. I can do this in useEffect with having cart in the box but I'm also fetching data in useEffect so each time the cart is updated my browser is refetching from an API. Is there a way I can do this without re fetching from the API?

React.useEffect(() => {
        async function fetchData() {
            const result = await axios(API)
            const items = result.data.data.items.map((item) => {
                item.count = 0
                return item
            })
            setProducts(items)
        }
        fetchData()
        setCalculatePrice(() =>
            cart.reduce((price, product) => price + product.price, 0).toFixed(2),
        )
    }, [cart])

updateCart function

const updateCart = React.useCallback(
        (product, index) => {
            const newCart = removeItemOnce(cart, product)
            products[index].count = products[index].count - 1
            setCart([...newCart])
            setProducts(products)
        },
        [cart, products],
    )

Upvotes: 0

Views: 40

Answers (1)

user3009269
user3009269

Reputation: 442

You can have separated useEffects. It's even advisable to have them separated. So in your case I would do:

React.useEffect(() => {
    async function fetchData() {
        const result = await axios(API)
        const items = result.data.data.items.map((item) => {
            item.count = 0
            return item
        })
        setProducts(items)
    }
    fetchData();
}, [])

This will be called on component mount once. And for cart update

React.useEffect(() => {
  setCalculatePrice(() =>
        cart.reduce((price, product) => price + product.price, 0).toFixed(2),
    );
}, [cart]);

Let me know how it goes!

Upvotes: 1

Related Questions