Home > Mobile >  How to run a fuction after when state updated?
How to run a fuction after when state updated?

Time:09-08

I have updateCart function. I want to run it when we reload the page and Cart state have some value. As we know useState hook renders two times on reload and empty on the first render and updates with values on the second render. I want this function run when state have some values i.e, on second render.

 const updateCart = () => {
        let newCart = { ...Cart }

        let keys = Object.keys(Cart)
        for (let i = 0; i < keys.length; i  ) {
            let previousPrice = Cart[keys[i]].price
            let currentPrice = allproducts[0].products.find(x => x.sku == keys[i]).product_price

            if (previousPrice != currentPrice) {
                newCart[keys[i]].price = currentPrice
            }
        }
        updateNewCart(newCart)

    }

    useEffect(() => {

        if (Object.keys(Cart).length != 0) {
            updateCart()
        }

    }, [])

CodePudding user response:

When ever update the change the cart value then automatically reload this useEffect function

useEffect(() => {
// Your code...

}, [cart])

CodePudding user response:

You can use a useLayoutEffect hook

This hook works synchronously. It runs immediately after React has performed all DOM mutations. It will run after every render but before the screen is updated.

This is how the useLayoutEffect hooks work step-by-step:

  1. A re-render was caused inside a React component.
  2. React renders your component.
  3. useLayoutEffect runs synchronously.
  4. React waits for the useLayoutEffect to finish running.
  5. The screen is updated.

You can use something like:

useLayoutEffect(() => {

if (Object.keys(Cart).length != 0) {
    updateCart()
}

}, [])

  • Related