-
Notifications
You must be signed in to change notification settings - Fork 6
/
useAccessToken.tsx
52 lines (43 loc) · 1.31 KB
/
useAccessToken.tsx
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
import AsyncStorage from "@react-native-async-storage/async-storage";
import React, { useState, createContext, useContext, 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 = useContext(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 AsyncStorage.getItem(ANILIST_ACCESS_TOKEN_STORAGE);
if (token) {
setAccessToken(token);
}
} finally {
setCheckedForToken(true);
}
})();
});
return (
<AccessTokenContext.Provider
value={{ accessToken, setAccessToken, checkedForToken }}
>
{children}
</AccessTokenContext.Provider>
);
}