-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathAuthContext.js
47 lines (40 loc) · 1.15 KB
/
AuthContext.js
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
import React, { createContext, useContext, useState } from "react";
import { AsyncStorage } from "react-native";
export const AuthContext = createContext();
export const AuthProvider = ({ isLoggedIn: isLoggedInProp, children }) => {
const [isLoggedIn, setIsLoggedIn] = useState(isLoggedInProp);
const logUserIn = async token => {
try {
await AsyncStorage.setItem("isLoggedIn", "true");
await AsyncStorage.setItem("jwt", token);
setIsLoggedIn(true);
} catch (e) {
console.log(e);
}
};
const logUserOut = async () => {
try {
await AsyncStorage.setItem("isLoggedIn", "false");
setIsLoggedIn(false);
} catch (e) {
console.log(e);
}
};
return (
<AuthContext.Provider value={{ isLoggedIn, logUserIn, logUserOut }}>
{children}
</AuthContext.Provider>
);
};
export const useIsLoggedIn = () => {
const { isLoggedIn } = useContext(AuthContext);
return isLoggedIn;
};
export const useLogIn = () => {
const { logUserIn } = useContext(AuthContext);
return logUserIn;
};
export const useLogOut = () => {
const { logUserOut } = useContext(AuthContext);
return logUserOut;
};