-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth-context.js
64 lines (57 loc) · 1.58 KB
/
auth-context.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import React from 'react';
import { useAsync } from 'react-async';
import * as authClient from './utils/auth-client';
import { bootstrapAppData } from './utils/bootstrap';
import FullPageSpinner from '../atoms/spinner';
const AuthContext = React.createContext();
function AuthProvider(props) {
const { client } = props;
const [firstAttemptFinished, setFirstAttemptFinished] = React.useState(false);
const {
data = { user: null, listItems: [] },
error,
isRejected,
isPending,
isSettled,
reload,
} = useAsync({
promiseFn: bootstrapAppData,
client,
});
React.useLayoutEffect(() => {
if (isSettled) {
setFirstAttemptFinished(true);
}
}, [isSettled]);
if (!firstAttemptFinished) {
if (isPending) {
return <FullPageSpinner />;
}
if (isRejected) {
return (
<div css={{ color: 'red' }}>
<p>Uh oh... There's a problem. Try refreshing the app.</p>
<pre>{error.message}</pre>
</div>
);
}
}
const login = form => authClient.login(form).then(reload);
const register = form => authClient.register(form).then(reload);
const logout = () => authClient.logout().then(reload);
const confirm = form => authClient.confirm(form).then(reload);
return (
<AuthContext.Provider
value={{ data, login, logout, register, confirm }}
{...props}
/>
);
}
function useAuth() {
const context = React.useContext(AuthContext);
if (context === undefined) {
throw new Error(`useAuth must be used within a AuthProvider`);
}
return context;
}
export { AuthProvider, useAuth };