Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/dashboard/src/hooks/use-user-loader.ts
2500 views
1
/**
2
* Copyright (c) 2022 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
import { useContext } from "react";
8
import { UserContext } from "../user-context";
9
import { trackLocation } from "../Analytics";
10
import { useQuery } from "@tanstack/react-query";
11
import { noPersistence } from "../data/setup";
12
import { ErrorCodes, ApplicationError } from "@gitpod/gitpod-protocol/lib/messaging/error";
13
import { userClient } from "../service/public-api";
14
15
export const useUserLoader = () => {
16
const { user, setUser } = useContext(UserContext);
17
18
// For now, we're using the user context to store the user, but letting react-query handle the loading
19
// In the future, we should remove the user context and use react-query to access the user
20
const { isLoading } = useQuery({
21
queryKey: noPersistence(["current-user"]),
22
queryFn: async () => {
23
const user = (await userClient.getAuthenticatedUser({})).user;
24
25
return user ?? null;
26
},
27
// We'll let an ErrorBoundary catch the error
28
useErrorBoundary: true,
29
// It's important we don't retry as we want to show the login screen as quickly as possible if a 401
30
retry: (_failureCount: number, error: Error & { code?: number }) => {
31
const isUserDeletedError = ApplicationError.isUserDeletedError(error);
32
return (
33
error.code !== ErrorCodes.NOT_AUTHENTICATED &&
34
error.code !== ErrorCodes.CELL_EXPIRED &&
35
!isUserDeletedError
36
);
37
},
38
// docs: https://tanstack.com/query/v4/docs/react/guides/query-retries
39
// backoff by doubling, max. 10s
40
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 10000),
41
cacheTime: 1000 * 60 * 60 * 1, // 1 hour
42
staleTime: 1000 * 60 * 60 * 1, // 1 hour
43
onSuccess: (loadedUser) => {
44
if (loadedUser) {
45
setUser(loadedUser);
46
}
47
},
48
onSettled: (loadedUser) => {
49
trackLocation(!!loadedUser);
50
},
51
});
52
53
return { user, loading: isLoading };
54
};
55
56