notrab / react-use-cart

React hook library for managing cart state
http://npm.im/react-use-cart
Apache License 2.0
367 stars 48 forks source link

Sync the cart's items between tabs #97

Closed mattjis closed 1 year ago

mattjis commented 2 years ago

If a customer opens multiple tabs, I want them to be able to seamlessly transition between them and the cart to always show the actual items. At the moment a refresh is required which isn't optimal for the user experience.

mattjis commented 2 years ago

I achieved this by doing the following:

import useWindowFocus from "use-window-focus"
import useLocalStorage from "use-local-storage-state"
const windowFocused = useWindowFocus()
const [cartStorage] = useLocalStorage("react-use-cart", null)

useEffect(() => {
  if (!windowFocused && cartStorage?.items) setItems(cartStorage.items)
}, [cartStorage])
notrab commented 2 years ago

Nice!

Perhaps we could add this to the library?

mattjis commented 2 years ago

@notrab Yeah sure, I think that would be a great idea.

I updated my snippet to work a bit nicer with Next.js

EDIT: Ideally it would keep everything in sync. The items, metadata etc

notrab commented 2 years ago

@mattjis is this something you'd like to create a PR for?