freshyo/apps/user-ui/src/components/PendingAddressSync.tsx
2026-11-14 21:26:25 +05:30

53 lines
1.6 KiB
TypeScript

import { useEffect, useRef } from 'react'
import { trpc } from '@/src/trpc-client'
import { useAuth } from '@/src/contexts/AuthContext'
import { clearPendingAddress, getPendingAddress } from '@/src/lib/pending-address'
/**
* Posts a locally-drafted address (created while signed out in the location
* fallback flow) once the user is authenticated. Also runs at order time,
* because ordering requires an account. The draft is kept on failure so it can
* be retried on the next authenticated mount.
*/
const PendingAddressSync: React.FC = () => {
const { isAuthenticated } = useAuth()
const utils = trpc.useUtils()
const createAddress = trpc.user.address.createAddress.useMutation()
const isSyncing = useRef(false)
useEffect(() => {
if (!isAuthenticated || isSyncing.current) return
let cancelled = false
const run = async () => {
const pending = await getPendingAddress()
if (!pending || cancelled) return
isSyncing.current = true
try {
await createAddress.mutateAsync(pending)
// The address is saved; clear the draft and refresh both lists together.
await Promise.all([
clearPendingAddress(),
utils.user.address.getUserAddresses.invalidate(),
utils.user.address.getDefaultAddress.invalidate(),
])
} catch {
// Leave the draft in place; a later authenticated mount retries it.
} finally {
isSyncing.current = false
}
}
void run()
return () => {
cancelled = true
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isAuthenticated])
return null
}
export default PendingAddressSync