forked from cristian-rita/react-native-jwt-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
49 lines (42 loc) · 1.29 KB
/
App.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
48
49
import React, {useCallback, useContext, useEffect, useState} from 'react';
import Login from './src/components/Login';
import {AuthContext} from './src/context/AuthContext';
import * as Keychain from 'react-native-keychain';
import Dashboard from './src/components/Dashboard';
import Spinner from './src/components/Spinner';
const App = () => {
const authContext = useContext(AuthContext);
const [status, setStatus] = useState('loading');
const loadJWT = useCallback(async () => {
try {
const value = await Keychain.getGenericPassword();
const jwt = JSON.parse(value.password);
authContext.setAuthState({
accessToken: jwt.accessToken || null,
refreshToken: jwt.refreshToken || null,
authenticated: jwt.accessToken !== null,
});
setStatus('success');
} catch (error) {
setStatus('error');
console.log(`Keychain Error: ${error.message}`);
authContext.setAuthState({
accessToken: null,
refreshToken: null,
authenticated: false,
});
}
}, []);
useEffect(() => {
loadJWT();
}, [loadJWT]);
if (status === 'loading') {
return <Spinner />;
}
if (authContext?.authState?.authenticated === false) {
return <Login />;
} else {
return <Dashboard />;
}
};
export default App;