AbiirSkincare/Hydrogen/web/app/hooks/useAbiirWishlistCount.ts

32 lines
995 B
TypeScript

import {useEffect, useState} from 'react';
import {
ABIIR_WISHLIST_CHANGE_EVENT,
readWishlistHandlesFromWindow,
} from '~/lib/abiirWishlistStorage';
/**
* Live wishlist size from localStorage (header badge, account tile). Reacts to
* `storage` (other tabs) and `abiir-wishlist-changed` (same tab).
*/
export function useAbiirWishlistCount() {
const [count, setCount] = useState(0);
useEffect(() => {
const sync = () => setCount(readWishlistHandlesFromWindow().length);
sync();
const onVis = () => {
if (document.visibilityState === 'visible') sync();
};
window.addEventListener(ABIIR_WISHLIST_CHANGE_EVENT, sync);
window.addEventListener('storage', sync);
document.addEventListener('visibilitychange', onVis);
return () => {
window.removeEventListener(ABIIR_WISHLIST_CHANGE_EVENT, sync);
window.removeEventListener('storage', sync);
document.removeEventListener('visibilitychange', onVis);
};
}, []);
return count;
}