umami/hooks/useRequireLogin.js

37 lines
718 B
JavaScript
Raw Normal View History

2020-08-05 07:45:05 +02:00
import { useState, useEffect } from 'react';
2020-10-01 07:34:16 +02:00
import { useRouter } from 'next/router';
import useUser from 'hooks/useUser';
2022-02-27 00:53:45 +01:00
import useApi from 'hooks/useApi';
2020-08-05 07:45:05 +02:00
2020-08-06 04:04:02 +02:00
export default function useRequireLogin() {
2020-10-01 07:34:16 +02:00
const router = useRouter();
2022-02-27 00:53:45 +01:00
const { get } = useApi();
const { user, setUser } = useUser();
const [loading, setLoading] = useState(false);
2020-08-05 07:45:05 +02:00
2020-10-01 07:34:16 +02:00
async function loadUser() {
setLoading(true);
2022-02-27 00:53:45 +01:00
const { ok, data } = await get('/auth/verify');
2020-10-01 07:34:16 +02:00
if (!ok) {
2022-02-27 00:53:45 +01:00
await router.push('/login');
return null;
2020-08-05 07:45:05 +02:00
}
setUser(data);
2020-08-05 07:45:05 +02:00
2020-10-01 07:34:16 +02:00
setLoading(false);
}
2020-08-05 07:45:05 +02:00
2020-10-01 07:34:16 +02:00
useEffect(() => {
2022-02-27 00:53:45 +01:00
if (loading || user) {
2020-10-01 07:34:16 +02:00
return;
}
2020-08-05 07:45:05 +02:00
2020-10-01 07:34:16 +02:00
loadUser();
2022-02-27 00:53:45 +01:00
}, [user, loading]);
2020-08-05 07:45:05 +02:00
return { user, loading };
}