-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathAuth.tsx
More file actions
55 lines (52 loc) · 1.72 KB
/
Auth.tsx
File metadata and controls
55 lines (52 loc) · 1.72 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
import { useEffect, useState } from "react";
import { UserInfo } from "remult";
import { API_URL } from "./api-url";
const Auth: React.FC<{ children: JSX.Element }> = ({ children }) => {
const [signInUsername, setSignInUsername] = useState("");
const [currentUser, setCurrentUser] = useState<UserInfo>();
const signIn = async () => {
const result = await fetch(API_URL + '/signIn', {
method: "POST",
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: signInUsername })
});
if (result.ok) {
setCurrentUser(await result.json());
setSignInUsername("");
}
else alert(await result.json());
}
const signOut = async () => {
await fetch(API_URL + '/signOut', {
method: "POST",
credentials: 'include'
});
setCurrentUser(undefined);
}
useEffect(() => {
fetch(API_URL + '/currentUser', {
credentials: 'include'
}).then(r => r.json())
.then(async currentUserFromServer => {
setCurrentUser(currentUserFromServer)
});
}, []);
if (!currentUser)
return (
<header>
<input value={signInUsername}
onChange={e => setSignInUsername(e.target.value)}
placeholder="Username, try Steve or Jane" />
<button onClick={signIn}>Sign in</button>
</header>);
return <>
<header>
Hello {currentUser.name} <button onClick={signOut}>Sign Out</button>
</header>
{children}
</>
}
export default Auth;