This repository has been archived on 2024-06-14. You can view files and clone it, but cannot push or open issues or pull requests.
icynet-admin/lib/hooks/useUser.ts

32 lines
832 B
TypeScript
Raw Normal View History

2022-08-29 18:09:28 +00:00
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 };
}