-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathContent.tsx
More file actions
120 lines (102 loc) · 2.81 KB
/
Content.tsx
File metadata and controls
120 lines (102 loc) · 2.81 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import React, { useCallback, useState } from 'react';
import type { DependencyList } from 'react';
import { useAuthClient } from './auth';
export const Content: React.FC = () => {
const authClient = useAuthClient();
const userCredentials = useUserCredentials();
const [doRegister, isRegisterLoading] = useAsyncCallback(
() =>
authClient.register({
email: userCredentials.email,
password: userCredentials.password,
}),
[authClient, userCredentials]
);
const [doLogin, isLoginLoading] = useAsyncCallback(
() => authClient.login(userCredentials),
[authClient, userCredentials]
);
const [doLogout, isLogoutLoading] = useAsyncCallback(
() => authClient.logout(),
[authClient]
);
return (
<div>
<p>Auth client ready? {String(authClient.isInitialized)}</p>
<p>Auth client authenticated? {String(authClient.isAuthenticated)}</p>
<div>
<input
type="email"
value={userCredentials.email}
onChange={userCredentials.updateEmail}
/>
<input
type="password"
value={userCredentials.password}
onChange={userCredentials.updatePassword}
/>
</div>
<div>
<button
onClick={doRegister}
disabled={authClient.isAuthenticated || isRegisterLoading}
>
Register
</button>
<button
onClick={doLogin}
disabled={authClient.isAuthenticated || isLoginLoading}
>
Login
</button>
<button
onClick={doLogout}
disabled={!authClient.isAuthenticated || isLogoutLoading}
>
Logout
</button>
</div>
{isRegisterLoading ? <p>Register in progress..</p> : null}
{isLoginLoading ? <p>Login in progress..</p> : null}
<p>Tokens:</p>
<pre>{JSON.stringify(authClient.tokens ?? {}, null, 2)}</pre>
</div>
);
};
function useUserCredentials() {
const [email, setEmail] = useState<string>('');
const [password, setPassword] = useState<string>('');
const updateEmail = useCallback(
(evt: React.ChangeEvent<HTMLInputElement>) => {
setEmail(evt.target.value);
},
[]
);
const updatePassword = useCallback(
(evt: React.ChangeEvent<HTMLInputElement>) => {
setPassword(evt.target.value);
},
[]
);
return {
email,
password,
updateEmail,
updatePassword,
};
}
function useAsyncCallback<T extends (...args: never[]) => Promise<unknown>>(
callback: T,
deps: DependencyList
): [T, boolean] {
const [isLoading, setLoading] = useState(false);
const cb = useCallback(async (...argsx: never[]) => {
setLoading(true);
try {
return await callback(...argsx);
} finally {
setLoading(false);
}
}, deps) as T;
return [cb, isLoading];
}