I created a simple navigation and login form.
What I did in app.js is pretty simple:
- guest user can access to "login" and "register" pages
- auth user can access to "home", "explore", "bookmarks" pages
App.js
const App = () => {
if (localStorage.getItem("token")) {
return (
<Router>
<div>
<ul>
<li>
<Link to="/home">Home</Link>
</li>
<li>
<Link to="/explore">explore</Link>
</li>
<li>
<Link to="/bookmarks">Bookmarks</Link>
</li>
</ul>
<Switch>
<Route exact path="/home">
<Home />
</Route>
<Route path="/explore">
<Explore />
</Route>
<Route path="/bookmarks">
<Bookmarks />
</Route>
</Switch>
</div>
</Router>
);
}
return (
<Router>
<div>
<Switch>
<Route exact path="/">
<Login />
</Route>
<Route path="/register">
<Register />
</Route>
</Switch>
</div>
</Router>
);
};
Once the user is logged I set a token and redirect to "/home" like so:
login.js
try {
let result = await loginRequest({ data });
localStorage.setItem("token", result.data.token);
history.push("/home");
} catch (errors) {
setError("un problème est survenu");
}
};
The request works and i'm redirected to "/home" but if I want to see the content of "/home" I have to refresh the page manually (using f5) otherwise I got a blank page.
Anyone can explain me why this behaviour ??