/
useUser.ts
80 lines (73 loc) · 1.99 KB
/
useUser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { useThirdwebAuthContext } from "../../contexts/thirdweb-auth";
import { cacheKeys } from "../../utils/cache-keys";
import { useQuery } from "@tanstack/react-query";
import type { Json, User } from "@thirdweb-dev/auth";
import invariant from "tiny-invariant";
import { AUTH_TOKEN_STORAGE_KEY } from "../../../core/constants/auth";
/**
* @auth
*/
export interface UserWithData<
TData extends Json = Json,
TContext extends Json = Json,
> extends User<TContext> {
data?: TData;
}
/**
* Hook for retrieving information about the currently signed-in user using [auth](https://portal.thirdweb.com/wallets/auth).
*
* Useful to get the user's address and session data, or `undefined` if no user is signed in.
*
* ```jsx
* import { useUser } from "@thirdweb-dev/react";
*
* function App() {
* const { user, isLoggedIn, isLoading } = useUser();
* }
* ```
*
* @auth
*
*/
export function useUser<
TData extends Json = Json,
TContext extends Json = Json,
>() {
const authConfig = useThirdwebAuthContext();
const { data: user, isLoading } = useQuery(
cacheKeys.auth.user(),
async () => {
invariant(
authConfig,
"Please specify an authConfig in the ThirdwebProvider",
);
invariant(
authConfig.authUrl,
"Please specify an authUrl in the authConfig.",
);
const token = await authConfig.secureStorage?.getItem(
AUTH_TOKEN_STORAGE_KEY,
);
// We include credentials so we can getUser even if API is on different URL
const params = {
credentials: "include",
...(token
? {
headers: {
Authorization: `Bearer ${token}`,
},
}
: {}),
};
const res = await fetch(
`${authConfig.authUrl}/user`,
params as RequestInit,
);
return (await res.json()) as UserWithData<TData, TContext>;
},
{
enabled: !!authConfig,
},
);
return { user, isLoggedIn: !!user, isLoading };
}