fix(shop): persist settings through backend
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
"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() {
|
||||
const [shop, setShop] = useState<Shop | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const refreshShop = useCallback(async () => {
|
||||
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)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
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
|
||||
}
|
||||
}, [])
|
||||
|
||||
return { shop, setShop, loading, error, refreshShop }
|
||||
}
|
||||
Reference in New Issue
Block a user