I'm new to React. My react app is running well but have a small problem. Whenever I navigate to some other pages and refresh the page there, then its coming back to home page.
App
const dispatch = useDispatch();
const loggedin = useSelector((state) => state.LoginSlice.loggedin);
useEffect(() => {
dispatch(check_login_status());
}, [dispatch]);
return (
<>
<Router>
{loggedin ? (
<div>
<LayoutAuth />
<br />
</div>
) : (
<div>{/* <LayoutNoauth /> */}</div>
)}
<div className="page_container">
<AppRoute loggedin={loggedin} />
</div>
</Router>
</>
);
AppRoute
function AppRoute({ loggedin }) {
return (
<Routes>
{!loggedin && (
<>
<Route path="/login" element={<LoginPage />} />
</>
)}
{loggedin && (
<>
<Route exact path="/" element={<HomePage />} />
<Route path="/home" element={<HomePage />} />
<Route path="/versions" element={<VersionPage />} />
<Route path="/pgeactivity" element={<PgeActivityPage />} />
</>
)}
<Route path="*" element={<Navigate to={loggedin ? "/home" : "/login"} />} /> //<-- this may be the problem
</Routes>
);
}
Note if I comment out the marked line in AppRoute, it is working but another problem arise that after log-in when I navigate to home page, on browser back button click it is navigating to log-in page again. Same thing happens on log-out.
I have attached a image please check it for clarification.
Anyone kindly suggest me what to do. Thank you.
The issue is with how you initialize loggedin
state in redux. When you initialize it will initialize with false and it requires a localStoreage change event or manually firing the event to call that useSelector
to update the value. But when you refresh it will take the default value as false and never to do changes until you do login/logout again.
To fix the issue you have to initialize loggedin
state in redux with the localStorage
state. Do change in Login.Slice.js
file.
const initialState = {
loggedin: localStorage.getItem("loggedin") === "yes"
};
You can have a working example at https://codesandbox.io/s/routing-demo-forked-f58q8p.
You can get details about localStorage. Its storage store data as key/value pair. localStorage.getItem("loggedin") === "yes"
will check does your localStorage with key loggedin
have value yes
. If yes then return true else false.
Also, localStorage.getItem("loggedin") === "yes"
is same as localStorage.getItem("loggedin") === "yes" ? true : false
. The first expression return true/false based on that you are doing condition. So if value is true then expression will be true ? true : false
which not make much sense.