-
Notifications
You must be signed in to change notification settings - Fork 9
/
Widget.jsx
90 lines (83 loc) · 2.32 KB
/
Widget.jsx
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
import React, { useState, useEffect } from "react";
import { useMutation } from "@apollo/react-hooks";
import netlifyIdentity from "netlify-identity-widget";
import gql from "graphql-tag";
import { Link, withRouter } from "react-router-dom";
import { getShortId } from "../format.js";
const REGISTER_USER = gql`
mutation registerUser {
registerUser
}
`;
export const Identity = withRouter(router => {
const [userId, setUserId] = useState(localStorage.getItem("userId"));
const [registerUser] = useMutation(REGISTER_USER);
const handleLogout = () => {
localStorage.removeItem("user");
localStorage.removeItem("userId");
localStorage.removeItem("token");
setUserId(null);
};
const handleLogin = async authenticatedUser => {
if (authenticatedUser) {
try {
const token = await authenticatedUser.jwt();
const shortId = getShortId(authenticatedUser.id);
localStorage.setItem("token", token);
localStorage.setItem("userId", shortId);
setUserId(shortId);
registerUser();
return;
} catch (e) {
console.log("Login failed", e);
}
}
handleLogout();
};
useEffect(() => {
netlifyIdentity.on("init", handleLogin);
netlifyIdentity.on("login", handleLogin);
netlifyIdentity.on("logout", handleLogout);
netlifyIdentity.init();
}, []);
if (!userId) {
return (
<div className="d-flex">
<button type="button" onClick={() => netlifyIdentity.open("signup")}>
Signup
</button>
<button
type="button"
className="ml-4"
onClick={() => netlifyIdentity.open("login")}
>
Login
</button>
</div>
);
}
const homeRoute = "/";
const isHomeRoute = router.location.pathname === homeRoute;
const isProfile = router.location.pathname.includes(userId);
return (
<div className="d-flex">
{!isHomeRoute && (
<Link to={homeRoute}>
<p className="Header-link mr-2">Home</p>
</Link>
)}
{!isProfile && (
<Link to={`/${getShortId(userId)}`}>
<p className="Header-link">Profile</p>
</Link>
)}
<button
type="button"
className="ml-4"
onClick={() => netlifyIdentity.logout()}
>
Logout
</button>
</div>
);
});