Reputation: 190
i am trying to create a login page in react using the code->
login.js
axios.get(apiUrl)
.then((result) => {
//console.log(result.data);
if (result.data.status === 200) {
// transfer to dashboard page
localStorage.setItem('isLoggedIn', true);
alert(result.data.message);
return navigate("/dashboard");
}
else
{
alert(result.data.message);
return navigate("/login");
}
}
)
now this will add a key-value pair in local storage.
now for my dashboard page i am using a navbar from 'responsive-navbar-react'
here is the code->
const NavbarDashboard = () => {
const props = {
items: [
{
text: 'Profile',
link: '/dashboard'
},
{
text: 'Logout',
link: '/',
}
],
logo: {
text: 'logo',
link: '/dashboard'
},
style: {
barStyles: {
background: '#444',
fontFamily: "'Lato', sans-serif",
},
sidebarStyles: {
background: '#222',
buttonColor: 'white'
}
}
}
return <Navbar {...props} />
}
export default NavbarDashboard;
this works fine. the value is set in local storage. but when i try to use the following code->
{
text: 'Logout',
link: '/',
onclick: localStorage.removeItem("isLoggedIn")
}
the value is not set in local storage when i try to login.
i want to add logout functionality on the button click. can someone help?
EDIT------------
creating a seperate logout component
import React from 'react';
function Logout() {
let navigate = useNavigate();
localStorage.removeItem('isLoggedIn')
return navigate("/");
}
export default Logout;
//end
Upvotes: 1
Views: 120
Reputation: 2665
{
text: 'Logout',
link: '/',
onclick: localStorage.removeItem("isLoggedIn")
}
In this code localStorage.removeItem("isLoggedIn")
is called immediately
you need to create anonymous function to wrap localStorage.removeItem("isLoggedIn")
{
text: 'Logout',
link: '/',
onclick: () => localStorage.removeItem("isLoggedIn")
}
Logout component
import React from "react"
import { Navigate } from "react-router-dom"
const Logout = () => {
useEffect(() => {
localStorage.removeItem("isLoggedIn")
}, [])
return <Navigate to="/" />
}
{
text: 'Logout',
link: '/logout'
}
Entry component
<Route path="/logout" element={<Logout/>}>
Upvotes: 3