mirror of
https://github.com/umami-software/umami.git
synced 2026-02-04 12:47:13 +01:00
Implement redux.
This commit is contained in:
parent
9d8a2406e1
commit
5d4ff5cfa4
31 changed files with 341 additions and 85 deletions
42
hooks/useUser.js
Normal file
42
hooks/useUser.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
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();
|
||||
}
|
||||
|
||||
export default function useUser() {
|
||||
const dispatch = useDispatch();
|
||||
const storeUser = useSelector(state => state.user);
|
||||
const [loading, setLoading] = useState(!storeUser);
|
||||
const [user, setUser] = useState(storeUser || null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!loading && user) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
fetchUser().then(async user => {
|
||||
if (!user) {
|
||||
window.location.href = '/login';
|
||||
return;
|
||||
}
|
||||
|
||||
await dispatch(updateUser({ user: user }));
|
||||
|
||||
setUser(user);
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return { user, loading };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue