32 lines
832 B
TypeScript
32 lines
832 B
TypeScript
|
import { useRouter } from 'next/router';
|
||
|
import { useEffect } from 'react';
|
||
|
import useSWR from 'swr';
|
||
|
import { CurrentUserDto } from '../types/user-response.interface';
|
||
|
|
||
|
export default function useUser({
|
||
|
redirectTo = '',
|
||
|
redirectIfFound = false,
|
||
|
} = {}) {
|
||
|
const router = useRouter();
|
||
|
const {
|
||
|
data: user,
|
||
|
mutate: mutateUser,
|
||
|
error,
|
||
|
} = useSWR<CurrentUserDto>('/api/user');
|
||
|
|
||
|
useEffect(() => {
|
||
|
if (!redirectTo) return;
|
||
|
|
||
|
if (
|
||
|
// If redirectTo is set, redirect if the user was not found.
|
||
|
(redirectTo && !redirectIfFound && !user && error) ||
|
||
|
// If redirectIfFound is also set, redirect if the user was found
|
||
|
(redirectIfFound && user && !error)
|
||
|
) {
|
||
|
router.push(redirectTo);
|
||
|
}
|
||
|
}, [user, error, router, redirectIfFound, redirectTo]);
|
||
|
|
||
|
return { user, mutateUser };
|
||
|
}
|