19

I'm currently trying to build a simple react-redux app that has student and campus data in the backend. OnEnter used to work here, but it doesn't exist in the new react-router.

This app tries to load initial data at the start instead of doing a componentDidMount in each actual component. Is that the recommended approach, or are there alternative patterns that I'm not aware of?

/* -------------------<    COMPONENT   >------------------- */
import React from 'react';

import { BrowserRouter as Router, Route } from 'react-router-dom';
import Home from './components/Home';
import Students from './components/Students';

const Routes = ({ getInitialData }) => {
  return (
    <Router>
      <div>
        <Route exact path="/" component={Home} onEnter={getInitialData} />
        <Route path="/students" component={Students} />
        <Route path="*" component={Home} />
      </div>
    </Router>
  );
};

/* -------------------<   CONTAINER   >-------------------- */

import { connect } from 'react-redux';
import receiveStudents from './reducers/student';
import receiveCampuses from './reducers/campus';

const mapState = null;
const mapDispatch = dispatch => ({
  getInitialData: () => {
    dispatch(receiveStudents());
    dispatch(receiveCampuses());
  }
});

export default connect(mapState, mapDispatch)(Routes);
fourestfire
  • 197
  • 1
  • 2
  • 8

4 Answers4

23

My current solution is to put extra code in render function and not to use component property.

<Route exact path="/" render={() => {
    getInitialData();
    return <Home />;
} } />
akmed0zmey
  • 553
  • 6
  • 14
  • 6
    The problem here is that if `getInitialData` is async, `` will render before it's done fetching. Not complaining to you, this is a fault of the v4 implementation. – Brandon Aaskov Jun 15 '17 at 21:41
  • 2
    In my applications I use some flag to show that data is loading and check it in the component. During loading process indicator is showing so it's not so bad for me – akmed0zmey Jun 16 '17 at 12:56
15

I want to suggest a bit different approach. Using class inheritance you can implement your own router.

import React from 'react';
import {Redirect, Route} from 'react-router';

/**
 * Class representing a route that checks if user is logged in.
 * @extends Route
 */
class AuthRequiredRoute extends Route{
  /**
   * @example <AuthRequiredRoute path="/" component={Products}>
   */
    render() {
        // call some method/function that will validate if user is logged in
        if(!loggedIn()){
            return <Redirect to="/login"></Redirect>
        }else{
          return <this.props.component />
        }
    }
}
sasklacz
  • 3,610
  • 10
  • 39
  • 58
wolendranh
  • 4,202
  • 1
  • 28
  • 37
11

One solution is to use HOC

function preCondition(condition, WrappedComponent) {
   return class extends Component {
     componentWillMount() {
       condition()
     }

      render() {
        <WrappedComponent {...this.props} />
      }
    }
}

<Route exact path="/" component={preCondition(getInitialData, Home )} />
Marty
  • 2,965
  • 4
  • 30
  • 45
Daniel Dai
  • 1,019
  • 11
  • 24
1
import React, { Component } from 'react';
import { Route, Redirect } from 'react-router-dom';

class LoginRoute extends Component{
    render() {
        const isLogin = () => {
            if () {
                return true;
            }
            return false;
        }
        if(!isLogin()){
            return <Redirect to="/login"></Redirect>
        }else{
            return <Route path={this.props.path} exact component={this.props.component} />
        }
    }
}

export default LoginRoute;
captain
  • 11
  • 2
  • @wolendranh thanks, it work for me! but this.props.history is undefined in component, so I change the code before – captain Jun 08 '18 at 08:19