score:13

Accepted answer

The most 'redux-like' way of handling the pre-loading of data would be to fire off the asynchronous action in the lifecycle method (probably componentWillMount) of a Higher Order Component that wraps your app. However, you will not use the results of the API call directly in that component - it needs to be handled with a reducer that puts it into your app store. This will require you to use some sort of a thunk middleware to handle the asynchronous action. Then you will use mapStateToProps to simply pass it down to the component that renders the data.

Higher Order Component:

const mapStateToProps = (state) => {
  return {
    departments: state.departments
  };
}

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({
    getDepartments: actionCreators.fetchDepartments
  });
}

class App extends Component {
  componentWillMount() {
    this.props.getDepartments();
  }

  render() {
    return <DepartmentsList departments={this.props.departments} />
  }
}

 export default connect(mapStateToProps, mapDispatchToProps)(App);

reducers:

export function departments(state = [], action) {
  switch(action.type) {
    case 'RECEIVE_DEPARTMENTS':
      return action.departments;
  }
}

Related Query

More Query from same tag