I am using the shopify-buy SDK, which allows me to retrieve the current cart of the user. I am trying to store that cart in my CartProvider which is then used in my Cart component. The problem is when I retrieve information from the cart it's acting a little slow so my component needs to be updated when the state changes, currently I have the following in my getShopifyCart function which is located in my CartProvider.
const [cartItems, setCartItems] = useState([])
const getShopifyCart = () => {
return client.checkout
.fetch(currentVendor.cartId)
.then((res) => {
const lineItemsData = res.lineItems.map((item) => {
return {
title: item.title,
quantity: item.quantity,
}
})
setCartItems(lineItemsData)
setLoading(false)
})
.catch((err) => console.log(err))
}
In my Cart component I have the following useEffect.
useEffect(() => {
getShopifyCart()
}, [cartItems])
But this causes an infinite loop, even though the cartItems state isn't changing.
You are setting the state cartItems inside getShopifyCart which you are calling inside a useEffect which has cartItems as a dependency. Even though the content of the data has not changed, you are creating a new object, hence its hash has changed as well which causes the useEffect to be called again.
If you want to initially fetch the data and set the state, then you need to pass an empty dependency array.
useEffect(() => {
getShopifyCart()
}, [])