umami/hooks/useRequireLogin.js

43 lines
888 B
JavaScript
Raw Normal View History

2020-08-05 07:45:05 +02:00
import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { updateUser } from 'redux/actions/user';
export async function fetchUser() {
const res = await fetch('/api/auth/verify');
if (!res.ok) {
return null;
}
return await res.json();
}
2020-08-06 04:04:02 +02:00
export default function useRequireLogin() {
2020-08-05 07:45:05 +02:00
const dispatch = useDispatch();
const storeUser = useSelector(state => state.user);
const [loading, setLoading] = useState(!storeUser);
2020-08-06 04:04:02 +02:00
const [user, setUser] = useState(storeUser);
2020-08-05 07:45:05 +02:00
useEffect(() => {
if (!loading && user) {
return;
}
setLoading(true);
fetchUser().then(async user => {
if (!user) {
window.location.href = '/login';
return;
}
2020-08-06 08:03:07 +02:00
await dispatch(updateUser(user));
2020-08-05 07:45:05 +02:00
setUser(user);
setLoading(false);
});
}, []);
return { user, loading };
}