With the code below, the logout button will only show if I refresh the page upon being successfully being logged in. The functionality works as intended, so no issues there.
Furthermore, I'd like to show the logout button on the navbar upon the user successfully logging in without refreshing page.
I've tried many ways to solve this but to no avail.
During my research, I came across something called Redux Persist but I'm unsure if it's worth using it in this scenario. Is there a way I can handle this without using Redux?
I'm open to code improvements/suggestions of my code. Thanks in advance.
import { Navbar, Nav, Container, Button } from 'react-bootstrap';
import axios from 'axios';
import { useHistory } from 'react-router-dom';
import {useEffect, useState} from "react";
const NavBar = () => {
let history = useHistory();
const [loggedInUser, setLoggedInUser] = useState("");
useEffect(() => {
const loggedInUser = localStorage.getItem("loginToken");
console.log(loggedInUser);
setLoggedInUser(loggedInUser);
});
const logout = (e) => {
e.preventDefault();
const headers = {
"Accept" : "application/json",
"Authorization" : `Bearer ${localStorage.getItem('loginToken')}`
};
axios.post('http://website.test/api/logout', null, {headers})
.then(res => {
console.log(res);
if(res.status === 200) {
localStorage.clear();
return history.push('/');
}
}).catch(err => {
console.log(err);
});
};
return (
<>
<Navbar bg="dark" variant="dark">
<Container>
<Navbar.Brand href="#home">Navbar</Navbar.Brand>
{ loggedInUser ? <Nav className="me-auto"><Button onClick={logout}>Logout</Button></Nav> : null }
</Container>
</Navbar>
</>
);
}
export default NavBar;
Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW
Comments
Post a Comment