react-use-cart icon indicating copy to clipboard operation
react-use-cart copied to clipboard

Sync the cart's items between tabs

Open mattjis opened this issue 4 years ago • 4 comments

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 avatar Nov 29 '21 08:11 mattjis

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])

mattjis avatar Dec 07 '21 02:12 mattjis

Nice!

Perhaps we could add this to the library?

notrab avatar Dec 07 '21 07:12 notrab

@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

mattjis avatar Dec 07 '21 08:12 mattjis

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

notrab avatar Jan 09 '22 09:01 notrab