AbiirSkincare/Hydrogen/web/app/components/WishlistServerSync.tsx

43 lines
1.0 KiB
TypeScript

import {useEffect, useRef} from 'react';
import {
readWishlistHandlesFromWindow,
writeWishlistHandles,
} from '~/lib/abiirWishlistStorage';
type SyncResponse = {
merged?: string[];
ok?: boolean;
};
/**
* On login, merges `localStorage` wishlist with `custom.abiir_wishlist` (JSON) when
* the customer metafield exists, then writes the union back to both.
*/
export function WishlistServerSync({isLoggedIn}: {isLoggedIn: boolean}) {
const ran = useRef(false);
useEffect(() => {
if (!isLoggedIn) {
ran.current = false;
return;
}
if (ran.current) return;
ran.current = true;
const handles = readWishlistHandlesFromWindow();
const fd = new FormData();
fd.set('handles', JSON.stringify(handles));
fetch('/api/wishlist-sync', {method: 'POST', body: fd})
.then((r) => r.json() as Promise<SyncResponse>)
.then((data) => {
if (Array.isArray(data.merged)) {
writeWishlistHandles(data.merged);
}
})
.catch(() => {});
}, [isLoggedIn]);
return null;
}