|
|
@@ -1,5 +1,5 @@
|
|
|
import { createContext, useContext, PropsWithChildren } from 'react'
|
|
|
-import Taro from '@tarojs/taro'
|
|
|
+import Taro, { useLaunch } from '@tarojs/taro'
|
|
|
import { authClient } from '../api'
|
|
|
import { InferResponseType, InferRequestType } from 'hono'
|
|
|
import { QueryClient, useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
|
|
@@ -65,13 +65,18 @@ export const AuthProvider: React.FC<PropsWithChildren> = ({ children }) => {
|
|
|
}
|
|
|
})
|
|
|
|
|
|
+
|
|
|
+
|
|
|
+ // 在小程序启动时执行静默登录,刷新token和sessionKey
|
|
|
+ useLaunch(() => {
|
|
|
+ silentLoginMutation.mutate()
|
|
|
+ })
|
|
|
+
|
|
|
const { data: user, isLoading } = useQuery<User | null, Error>({
|
|
|
queryKey: ['currentUser'],
|
|
|
queryFn: async () => {
|
|
|
const token = Taro.getStorageSync('mini_token')
|
|
|
if (!token) {
|
|
|
- // 如果没有token,尝试静默登录
|
|
|
- silentLoginMutation.mutate()
|
|
|
return null
|
|
|
}
|
|
|
try {
|
|
|
@@ -83,8 +88,7 @@ export const AuthProvider: React.FC<PropsWithChildren> = ({ children }) => {
|
|
|
Taro.setStorageSync('userInfo', JSON.stringify(user))
|
|
|
return user
|
|
|
} catch (error) {
|
|
|
- // token无效,尝试静默登录
|
|
|
- silentLoginMutation.mutate()
|
|
|
+ // token无效,清除存储
|
|
|
Taro.removeStorageSync('mini_token')
|
|
|
Taro.removeStorageSync('userInfo')
|
|
|
return null
|