I'm using localStorage to save user data on login. I've saved it named "jwt_data". I've created a function on saperate js file to retrieve that data as
export const auth = () => {
if(localStorage.getItem('jwt_data')){
return JSON.parse(localStorage.getItem('jwt_data'))
}else{
return false
}
}
and i've a navbar component on react with < logo , searchbar, a dropdown>. I wanted to hide that once user logout and show once i login . I used code as
const auth_user = auth()
........
<>
{auth_user ? (// if logged in..... ) : (// if user is logged out........)
</>
It did worked. But problem is it is not reactive. I need to reload the website to see that effect.
I also tried to use other such as
const [auth_user, setAuth_user] = useState(false)
useEffect(() => {
if(auth()) {setAuth_user(true)}
else {setAuth_user(false)}
})
Which have same result as previous. I dont know where i'm wrong. Other people suggested to use redux and things, which is too complicated for my mind and my simple application.
My app.js look like this
import React from 'react';
import Nav from './Nav';
import Home from './Home';
import Login from './Login';
import Logout from './Logout';
function App() {
return (
<div className="App">
<Router>
<Router>
<Nav/>
<Routes>
<Route exact path="/home" element={<Home/>}/>
<Route exact path="/login" element={<Login/>}/>
<Route exact path="/logout" element={<Logout/>}/>
</Routes>
</Router>
</div>
);
}
After I login, im moved to home and while doing so , i wanted to remove all the things in navbar have that is only shown that is authenticated, like in this case and also general other scenario.
Any thing i'm missing here ? Thank you for your kind answer.