React Router v4 - Redirect to home on page reload inside application

18.4k views Asked by At

I need to redirect to home page when user refreshes other pages inside my application. I am using React router v4 and redux. Since the store is lost on reload, the page user reloaded is now empty and hence I want to take him back to a page that does not need any previous stored data. I don't want to retain state in localStorage.

I tried to handle this in event onload but it did not work:

window.onload = function() {
    window.location.path = '/aaaa/' + getCurrentConfig();
};
2

There are 2 answers

0
AmerllicA On

It is so amazing that you don't want to keep state of user route map in browser but you use react-router!, the main solution for your case is do not use react-router.

If you don't use it, after each refresh the app come back to main view of app, If you wanna see route map in address bar without any reaction use JavaScript history pushState.

Hope it helps you.

1
Murli Prajapati On

You can try creating a new route component, say RefreshRoute and check for any state data you need. If the data is available then render the component else redirect to home route.

import React from "react";
import { connect } from "react-redux";
import { Route, Redirect } from "react-router-dom";

const RefreshRoute = ({ component: Component, isDataAvailable, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      isDataAvailable ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/home"
          }}
        />
      )
    }
  />
);

const mapStateToProps = state => ({
  isDataAvailable: state.reducer.isDataAvailable
});

export default connect(mapStateToProps)(RefreshRoute);  

Now use this RefreshRoute in your BrowserRouter as like normal Route.

<BrowserRouter>
  <Switch>
    <Route exact path="/home" component={Home} />
    <RefreshRoute exact path="dashboard" component={Dashboard} />
    <RefreshRoute exact path="/profile" component={ProfileComponent} />
  </Switch>
</BrowserRouter>