2022-12-29 00:43:22 +01:00
|
|
|
import { useEffect } from 'react';
|
|
|
|
import { useRouter } from 'next/router';
|
2022-02-23 07:47:59 +01:00
|
|
|
import useStore, { setUser } from 'store/app';
|
2022-12-29 00:43:22 +01:00
|
|
|
import useApi from 'hooks/useApi';
|
2022-02-23 07:47:59 +01:00
|
|
|
|
|
|
|
const selector = state => state.user;
|
2022-12-29 00:43:22 +01:00
|
|
|
let loading = false;
|
2022-02-23 07:47:59 +01:00
|
|
|
|
|
|
|
export default function useUser() {
|
|
|
|
const user = useStore(selector);
|
2022-12-29 00:43:22 +01:00
|
|
|
const { get } = useApi();
|
|
|
|
const router = useRouter();
|
2022-02-23 07:47:59 +01:00
|
|
|
|
2022-12-29 00:43:22 +01:00
|
|
|
useEffect(() => {
|
|
|
|
async function loadUser() {
|
|
|
|
const { user } = await get('/auth/verify');
|
|
|
|
loading = false;
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
await router.push('/login');
|
|
|
|
} else {
|
|
|
|
setUser(user);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!user && !loading) {
|
|
|
|
loading = true;
|
|
|
|
loadUser();
|
|
|
|
}
|
|
|
|
}, [user, get, router]);
|
|
|
|
|
|
|
|
return user;
|
2022-02-23 07:47:59 +01:00
|
|
|
}
|