plane/apps/app/hooks/use-user.tsx
sriram veeraghanta 44f8ba407d
Authentication Workflow fixes. Redirection fixes (#832)
* auth integration fixes

* auth integration fixes

* auth integration fixes

* auth integration fixes

* dev: update user api to return fallback workspace and improve the structure of the response

* dev: fix the issue keyerror and move onboarding logic to serializer method field

* dev: use-user-auth hook imlemented for route access validation and build issues resolved effected by user payload

* fix: global theme color fix

* style: new onboarding ui , fix: use-user-auth hook implemented

* fix: command palette, project invite modal and issue detail page mutation type fix

* fix: onboarding redirection fix

* dev: build isuue resolved

* fix: use user auth hook fix

* fix: sign in toast alert fix, sign out redirection fix and user theme error fix

* fix: user response fix

* fix: unAuthorizedStatus logic updated

---------

Co-authored-by: pablohashescobar <nikhilschacko@gmail.com>
Co-authored-by: gurusainath <gurusainath007@gmail.com>
Co-authored-by: anmolsinghbhatia <anmolsinghbhatia@caravel.tech>
2023-05-30 19:14:35 +05:30

56 lines
1.7 KiB
TypeScript

import { useEffect } from "react";
import { useRouter } from "next/router";
import useSWR from "swr";
// services
import userService from "services/user.service";
// constants
import { CURRENT_USER } from "constants/fetch-keys";
// types
import type { ICurrentUserResponse, IUser } from "types";
export default function useUser({ redirectTo = "", redirectIfFound = false, options = {} } = {}) {
const router = useRouter();
// API to fetch user information
const { data, isLoading, error, mutate } = useSWR<ICurrentUserResponse>(
CURRENT_USER,
() => userService.currentUser(),
options
);
const user = error ? undefined : data;
// console.log("useUser", user);
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 (
// If redirectTo is set, redirect if the user was not found.
(redirectTo && !redirectIfFound) ||
// If redirectIfFound is also set, redirect if the user was found
(redirectIfFound && user)
) {
router.push(redirectTo);
return;
// const nextLocation = router.asPath.split("?next=")[1];
// if (nextLocation) {
// router.push(nextLocation as string);
// return;
// } else {
// router.push("/");
// return;
// }
}
}, [user, redirectIfFound, redirectTo, router]);
return {
user,
isUserLoading: isLoading,
mutateUser: mutate,
userError: error,
assignedIssuesLength: user?.assigned_issues ?? 0,
workspaceInvitesLength: user?.workspace_invites ?? 0,
};
}