-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathuseAccessToken.tsx
More file actions
54 lines (45 loc) · 1.28 KB
/
useAccessToken.tsx
File metadata and controls
54 lines (45 loc) · 1.28 KB
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
import * as SecureStore from "expo-secure-store";
import React, { useState, createContext, use, useEffect } from "react";
import { ANILIST_ACCESS_TOKEN_STORAGE } from "yep/constants";
type AccessTokenContextValue = {
accessToken?: string;
checkedForToken: boolean;
setAccessToken: (accountName?: string) => void;
};
const AccessTokenContext = createContext<AccessTokenContextValue | null>(null);
export function useAccessToken() {
const context = use(AccessTokenContext);
if (context === null) {
throw new Error("useAccessToken must be used within a AccessTokenProvider");
}
return context;
}
export function AccessTokenProvider({
children,
}: {
children: React.ReactNode;
}) {
const [accessToken, setAccessToken] = useState<string | undefined>();
const [checkedForToken, setCheckedForToken] = useState(false);
useEffect(function fetchToken() {
(async () => {
try {
const token = await SecureStore.getItemAsync(
ANILIST_ACCESS_TOKEN_STORAGE
);
if (token) {
setAccessToken(token);
}
} finally {
setCheckedForToken(true);
}
})();
});
return (
<AccessTokenContext
value={{ accessToken, setAccessToken, checkedForToken }}
>
{children}
</AccessTokenContext>
);
}