1
0
Fork 0
mirror of https://github.com/muerwre/vault-frontend.git synced 2025-04-25 12:56:41 +07:00
vault-frontend/src/hooks/profile/useGetProfile.ts
2022-01-19 12:30:04 +07:00

36 lines
921 B
TypeScript

import { useCallback } from 'react';
import useSWR from 'swr';
import { apiAuthGetUserProfile } from '~/api/auth';
import { API } from '~/constants/api';
import { EMPTY_USER } from '~/constants/auth';
import { IUser } from '~/types/auth';
const getKey = (username?: string): string | null => {
return username ? `${API.USER.PROFILE}/${username}` : null;
};
export const useGetProfile = (username?: string) => {
const { data, isValidating, mutate } = useSWR(
getKey(username),
async () => {
const result = await apiAuthGetUserProfile({ username: username || '' });
return result.user;
},
{
refreshInterval: 60000,
}
);
const profile = data || EMPTY_USER;
const update = useCallback(
async (user: Partial<IUser>) => {
await mutate({ ...profile, ...user });
},
[mutate, profile]
);
return { profile, isLoading: !data && isValidating, update };
};