Hydration error
kasperaamodt opened this issue · comments
Hello,
I'm getting a hydration error in Next JS with React 18 when I use this package. Any idea how to fix this?
An example is when I have an item in my cart, and I show the number of products in the cart, I get an hydration error. Because on the server, the number rendered on the screen is 0, but on the client, the number i 1.
@kasperaamodt did you fix it? I'm still facing this problem
In my case, I resolved this by always using the getters/setters within useEffect
hooks or event listeners, like in this example.
const { cartTotal, items } = useCart()
const [ cartTotalFormatted, setCartTotalFormatted ] = useState(null)
useEffect(() => {
setCartTotalFormatted(new Intl.NumberFormat('en-AU', { style: 'currency', currency: 'AUD' }).format(cartTotal))
})
@ramiroazar does this also affect the items object since your solution only worked when using the cartTotal, but when I use the items object to display the cart items, the hydration error hits back!
Apparently in addition to @ramiroazar solution, the items object shall be also refactored as so:
const { items, emptyCart, removeItem, updateItemQuantity } = useCart()
const [allItems, setallItems] = useState([{}])
useEffect(() => {
setallItems(JSON.parse(JSON.stringify(items)))
}, [items])
and then use allItems
instead of items
Sorry, @FirasRihanSCMP, I meant to get back to you earlier.
That looks right to me, it's pretty much how I've been approaching it.
Is stringifying/parsing the items array necessary?
@ramiroazar yes it is necessary only for the items object, I still don't know why but I used to use this approach in object props returned from getServerSideProps and it worked for the react-use-cart
Try these examples! :) https://traviswimer.com/blog/easily-fix-react-hydration-errors/