50 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-05-12 02:45:43 +08:00
import { fetchUserAccount } from '@/web/api/user'
2022-04-16 21:14:03 +08:00
import { UserApiNames, FetchUserAccountResponse } from '@/shared/api/User'
2023-01-28 11:54:57 +08:00
import { CacheAPIs } from '@/shared/CacheAPIs'
2022-04-16 21:14:03 +08:00
import { IpcChannels } from '@/shared/IpcChannels'
2022-10-28 20:29:04 +08:00
import { useMutation, useQuery } from '@tanstack/react-query'
2023-03-03 03:12:27 +08:00
import { logout as logoutAPI } from '../auth'
2022-10-28 20:29:04 +08:00
import { removeAllCookies } from '@/web/utils/cookie'
import reactQueryClient from '@/web/utils/reactQueryClient'
2022-03-13 14:40:38 +08:00
export default function useUser() {
2022-10-28 20:29:04 +08:00
const key = [UserApiNames.FetchUserAccount]
return useQuery(
key,
async () => {
const existsQueryData = reactQueryClient.getQueryData(key)
if (!existsQueryData) {
window.ipcRenderer
?.invoke(IpcChannels.GetApiCache, {
2023-01-28 11:54:57 +08:00
api: CacheAPIs.UserAccount,
2022-10-28 20:29:04 +08:00
})
.then(cache => {
if (cache) reactQueryClient.setQueryData(key, cache)
})
}
return fetchUserAccount()
},
{
refetchOnWindowFocus: true,
}
)
}
2023-03-03 03:12:27 +08:00
export const useIsLoggedIn = () => {
const { data, isLoading } = useUser()
if (isLoading) return true
return !!data?.profile?.userId
}
export const logout = async () => {
await logoutAPI()
removeAllCookies()
await window.ipcRenderer?.invoke(IpcChannels.Logout)
await reactQueryClient.refetchQueries([UserApiNames.FetchUserAccount])
}
2022-10-28 20:29:04 +08:00
export const useMutationLogout = () => {
2023-03-03 03:12:27 +08:00
return useMutation(logout)
2022-03-13 14:40:38 +08:00
}