I am trying to create a login functionality where if the user is logged in he/she should be redirected to /health page but if he/she is not logged in , the user should be automatically redirected to /login page. While doing this I came across the concept of local storage I understood and tried implementing it. However, it is not fetching the desired results.
From what I can tell you are missing initializing your isLog state from localStorage. After a user authenticates you set the storage and redirect to the "/health" route, but if a user is already logged in and reloads the page, the App will reinitialize its isLog state back to false.
Using a state lazy initializer function you can read the localStorage for the isLog key and set the initial state.
const [isLog, setState] = useState(() => {
return !!JSON.parse(localStorage.getItem("isLog"));
});
You can also simplify your redirect logic by moving it below all your routes other then the "404" match all routes.
Example:
<Switch>
<Route path="/login">
<Login isLogIn={handleLogin} />
</Route>
<Route path="/health" component={Health} />
<Route path="/useradmin" component={UserAdmin} />
<Redirect exact from="/" to={isLog ? "/health" : "/login"} />
<Route path="*">NOT FOUND</Route>
</Switch>