Path: blob/main/components/dashboard/src/hooks/use-user-loader.ts
2500 views
/**1* Copyright (c) 2022 Gitpod GmbH. All rights reserved.2* Licensed under the GNU Affero General Public License (AGPL).3* See License.AGPL.txt in the project root for license information.4*/56import { useContext } from "react";7import { UserContext } from "../user-context";8import { trackLocation } from "../Analytics";9import { useQuery } from "@tanstack/react-query";10import { noPersistence } from "../data/setup";11import { ErrorCodes, ApplicationError } from "@gitpod/gitpod-protocol/lib/messaging/error";12import { userClient } from "../service/public-api";1314export const useUserLoader = () => {15const { user, setUser } = useContext(UserContext);1617// For now, we're using the user context to store the user, but letting react-query handle the loading18// In the future, we should remove the user context and use react-query to access the user19const { isLoading } = useQuery({20queryKey: noPersistence(["current-user"]),21queryFn: async () => {22const user = (await userClient.getAuthenticatedUser({})).user;2324return user ?? null;25},26// We'll let an ErrorBoundary catch the error27useErrorBoundary: true,28// It's important we don't retry as we want to show the login screen as quickly as possible if a 40129retry: (_failureCount: number, error: Error & { code?: number }) => {30const isUserDeletedError = ApplicationError.isUserDeletedError(error);31return (32error.code !== ErrorCodes.NOT_AUTHENTICATED &&33error.code !== ErrorCodes.CELL_EXPIRED &&34!isUserDeletedError35);36},37// docs: https://tanstack.com/query/v4/docs/react/guides/query-retries38// backoff by doubling, max. 10s39retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 10000),40cacheTime: 1000 * 60 * 60 * 1, // 1 hour41staleTime: 1000 * 60 * 60 * 1, // 1 hour42onSuccess: (loadedUser) => {43if (loadedUser) {44setUser(loadedUser);45}46},47onSettled: (loadedUser) => {48trackLocation(!!loadedUser);49},50});5152return { user, loading: isLoading };53};545556