"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(null) const [loading, setLoading] = useState(enabled) const [error, setError] = useState(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 } }