React Router - Stay At the Same Page After Refresh

React Router - Stay at the same page after refresh

Check that firebase does not interfares with the client side routes :P

You can use Index routes to achieve this.

You have your navigation i.e the layout of all pages in your app component so make it the root route.

Then you want your home route to be your default route so make it your Index route.

You need to import IndexRoute from react-router package (from which you import Route).

Add this-

import { Router, Route, IndexRoute } from 'react-router';

and then make your routes like below.

Use this-

<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/home" component={Home}/>
<Route path="/allhotels" component={AllHotels}/>
<Route path="/addhotel" component={AddHotel} />
<Route path="/about" component={About} />
</Route>
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
</Router>
</Provider>, document.getElementById('root')

React - How to stay on the same page even if it was refreshed?

is there any way to stick on the same page even after refreshing in react router?

From what I can tell, after navigating to one of the nested routes and reloading the page, the app reloads and the authorized state is reset and the child route component checks this state and imperatively redirects back.

Persist and initialize the authorized state to/from localStorage.

class App extends React.Component {
state = {
// Read initial state from localStorage, provide fallback
authorized: JSON.parse(localStorage.getItem("authorized")) ?? false,
extras: {}
}

componentDidUpdate(prevProps, prevState) {
// Persist authorized state changes to localStorage
if (prevState.authroized !== this.state.authorized) {
localStorage.setItem("authorized", JSON.stringify(authorized));
}
}

authorizeUser = (authorizeState, extras) => {
console.log('called 1');
this.setState({
authorized: authorizeState,
extras: extras
})
}
render() {
return (
<Routes>
<Route path='/editor' element={<EditorPage />} />
<Route
path='/panel/articleverification'
element={(
<LoginPageForArticalVerificationPanel
authorizeUser={this.authorizeUser}
/>
)}
/>
<Route
path='/panel/articleverification/homepage'
element={(
<HomePageForArticalVerificationPanel
authorized={this.state.authorized}
/>
)}
/>
<Route
path='/panel/articleverification/articlepage'
element={(
<ArticlePageForArticalVerificationPanel
authorized={this.state.authorized}
/>
)}
/>
</Routes>
);
}
}

Refresh on the same page in React

The issue is most likely that your ProtectedRoute component is using the initial isLoggedIn state from Redux to determine auth status before the useEffect has a chance to read from localStorage and update the redux state.

I don't know what your initial isLoggedIn reducer state looks like, but you'll want to make the initial value an "indeterminate" value, that is to say, a value that is neither true or false. undefined or null are good candidates.

From here the ProtectedRoute component will need to handle this third "indeterminant" state and not render either the children prop or the Navigate component redirect.

Here's an example ProtectedRoute component:

const ProtectedRoute = ({ children }) => {
const location = useLocation();
const isLoggedIn = useSelector(isLoggedInSelector);

if (isLoggedIn === undefined) return "... LOADING ...";

return isLoggedIn ? (
children
) : (
<Navigate to="/" replace state={{ from: location }} />
);
};

When a user is already authenticated and the isLoggedIn state resolves/updates to a truthy value, the route they are currently on will be accessible and returned and rendered.

When a user is unauthenticated the the isLoggedIn state resolves/updates to a non-undefined falsey value, the current location is sniffed and they are redirected to your login route. The location is passed so the user can be redirected back to the route they were originally attempting to access.

Here's a running codesandbox demo:

Edit refresh-on-the-same-page-in-react

You can also simplify your routes function a bit, if no element prop is specified an Outlet is rendered by default.

const routes = ({ isLoggedIn }) => [
{
path: "/",
children: [
{
index: true,
element: !isLoggedIn ? <Login /> : <Navigate to="/main" />
},
{
path: "/main",
element: (
<ProtectedRoute>
<MainPage />
</ProtectedRoute>
)
},
{
path: "/main/:id",
element: (
<ProtectedRoute>
<DetailPage />
</ProtectedRoute>
)
}
]
}
];


Related Topics



Leave a reply



Submit