Improved the whole user usage

This commit is contained in:
Tiago Ribeiro
2023-05-01 19:49:56 +01:00
parent 06de06fbf6
commit 4b5c99c654
5 changed files with 24 additions and 36 deletions

View File

@@ -7,15 +7,12 @@ import axios from "axios";
const fetcher = (url: string) => axios.get(url).then((res) => res.data);
export default function useUser({redirectTo = "", redirectIfFound = false} = {}) {
const {data: user, mutate: mutateUser, isLoading} = useSWR<User>("/api/user", fetcher);
const {data: user, mutate: mutateUser, isLoading, error} = useSWR<User>("/api/user", fetcher);
useEffect(() => {
// if no redirect needed, just return (example: already on /dashboard)
// if user data not yet there (fetch in progress, logged in or not) then don't do anything yet
if (!redirectTo || !user) return;
if (redirectTo && !user) {
Router.push(redirectTo);
}
if (
// If redirectTo is set, redirect if the user was not found.
@@ -25,7 +22,7 @@ export default function useUser({redirectTo = "", redirectIfFound = false} = {})
) {
Router.push(redirectTo);
}
}, [user, redirectIfFound, redirectTo]);
}, [user, redirectIfFound, redirectTo, error]);
return {user, mutateUser, isLoading};
}