notrab / react-use-cart

React hook library for managing cart state

Home Page:http://npm.im/react-use-cart

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Sync the cart's items between tabs

mattjis opened this issue · 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.

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

Nice!

Perhaps we could add this to the library?

@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 is this something you'd like to create a PR for?