Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
};
like image 806
Peter Avatar asked Jun 27 '18 04:06

Peter


1 Answers

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>
like image 172
Murli Prajapati Avatar answered Sep 23 '22 04:09

Murli Prajapati