Files
juwan-frontend/lib/hooks/use-my-shop.ts
T
2026-04-25 15:04:48 +08:00

73 lines
1.7 KiB
TypeScript

"use client"
import { getMyShop } from "@/lib/api/shops"
import { toApiError } from "@/lib/errors"
import type { Shop } from "@/lib/types"
import { useCallback, useEffect, useState } from "react"
export function useMyShop(enabled = true) {
const [shop, setShop] = useState<Shop | null>(null)
const [loading, setLoading] = useState(enabled)
const [error, setError] = useState<string | null>(null)
const refreshShop = useCallback(async () => {
if (!enabled) return null
setLoading(true)
setError(null)
try {
const nextShop = (await getMyShop()) ?? null
setShop(nextShop)
return nextShop
} catch (error) {
setShop(null)
setError(
error instanceof Error && error.message === "UNAUTHORIZED"
? "请先登录"
: toApiError(error).msg,
)
return null
} finally {
setLoading(false)
}
}, [enabled])
useEffect(() => {
if (!enabled) return
let cancelled = false
Promise.resolve()
.then(() => {
if (cancelled) return undefined
setLoading(true)
setError(null)
return getMyShop()
})
.then((nextShop) => {
if (cancelled) return
setShop(nextShop ?? null)
})
.catch((error) => {
if (cancelled) return
setShop(null)
setError(
error instanceof Error && error.message === "UNAUTHORIZED"
? "请先登录"
: toApiError(error).msg,
)
})
.finally(() => {
if (cancelled) return
setLoading(false)
})
return () => {
cancelled = true
}
}, [enabled])
return { shop, setShop, loading, error, refreshShop }
}