node-mongo-demo
node.js and mongodb demo
git clone https://9o.is/git/node-mongo-demo.git
Navbar.js
(2481B)
1 import React, { useState, useEffect } from "react";
2 import { AppBar, Typography, Toolbar, Avatar, Button } from "@mui/material";
3 import { Link, useNavigate, useLocation } from "react-router-dom";
4 import { useDispatch } from "react-redux";
5 import { jwtDecode } from "jwt-decode";
6 import * as actionType from "../../constants/actionTypes";
7 import { styles } from "./styles";
8
9 const Navbar = () => {
10 const [user, setUser] = useState(
11 localStorage.getItem("profile")
12 ? jwtDecode(JSON.parse(localStorage.getItem("profile")).token)
13 : "null"
14 );
15 const dispatch = useDispatch();
16 let location = useLocation();
17 const history = useNavigate();
18
19 const logout = () => {
20 dispatch({ type: actionType.LOGOUT });
21 history("/auth");
22 setUser("null");
23 };
24
25 useEffect(() => {
26 if (user !== "null" && user !== null) {
27 if (user.exp * 1000 < new Date().getTime()) logout();
28 }
29 setUser(
30 localStorage.getItem("profile")
31 ? jwtDecode(JSON.parse(localStorage.getItem("profile")).token)
32 : "null"
33 );
34 }, [location]);
35
36 return (
37 <AppBar sx={styles.appBar} position="static" color="inherit">
38 <div sx={styles.brandContainer}>
39 <Typography
40 component={Link}
41 to="/"
42 sx={styles.heading}
43 variant="h5"
44 align="center"
45 >
46 CoinToss
47 </Typography>
48 </div>
49 <Toolbar sx={styles.toolbar}>
50 {user !== "null" && user !== null ? (
51 <div sx={styles.profile}>
52 <Avatar sx={styles.purple} alt={user.name} src={user.picture}>
53 {user.name.charAt(0)}
54 </Avatar>
55 <Typography sx={styles.userName} variant="h6">
56 {user.name}
57 </Typography>
58 <Button
59 variant="contained"
60 sx={styles.logout}
61 color="secondary"
62 onClick={logout}
63 >
64 Logout
65 </Button>
66 <Button
67 variant="contained"
68 color="secondary"
69 onClick={() => {
70 history("/password");
71 }}
72 >
73 Set Password
74 </Button>
75 </div>
76 ) : (
77 <Button
78 component={Link}
79 to="/auth"
80 variant="contained"
81 color="primary"
82 >
83 Login
84 </Button>
85 )}
86 </Toolbar>
87 </AppBar>
88 );
89 };
90
91 export default Navbar;