AndrewMcLagan AndrewMcLagan - 1 year ago 447
React JSX Question

React-Router: how to wait for an async action before route transition

Is it possible to call an async redux action known as a

on a particular route and not perform the transition until the response has succeeded or failed?

Use Case

We need to load data from the server and fill a form with initial values. These initial values don't exist until the data is fetched from the server.

some syntax like this would be great:

<Route path="/myForm" component={App} async={dispatch(loadInitialFormValues(formId))}>

Answer Source

To answer the original question of preventing the transition to a new route until a response has succeeded or failed:

Because you're using redux thunk you could have the success or failure in the action creator trigger the redirect. I don't know what your specific action / action creator looks like but something like this could work:

import { browserHistory } from 'react-router'

export function loadInitialFormValues(formId) {
  return function(dispatch) {
    // hit the API with some function and return a promise:
      .then(response => {
        // If request is good update state with fetched data
        dispatch({ type: UPDATE_FORM_STATE, payload: response });

        // - redirect to the your form
      .catch(() => {
        // If request is bad...
        // do whatever you want here, or redirect

Follow up. Common pattern of loading data on entering a route / on componentWillMount of a component and displaying a spinner:

From the redux docs on async actions

  • An action informing the reducers that the request began.

The reducers may handle this action by toggling an isFetching flag in the state. This way the UI knows it’s time to show a spinner.

  • An action informing the reducers that the request finished successfully.

The reducers may handle this action by merging the new data into the state they manage and resetting isFetching. The UI would hide the spinner, and display the fetched data.

  • An action informing the reducers that the request failed.

The reducers may handle this action by resetting isFetching. Additionally, some reducers may want to store the error message so the UI can display it.

I followed this general pattern below using your situation as a rough guideline. You do not have to use promises

// action creator:
export function fetchFormData(formId) {
  return dispatch => {
    // an action to signal the beginning of your request
    // this is what eventually triggers the displaying of the spinner
    dispatch({ type: FETCH_FORM_DATA_REQUEST })

    // (axios is just a promise based HTTP library)
      .then(formData => {
        // on successful fetch, update your state with the new form data
        // you can also turn these into their own action creators and dispatch the invoked function instead
        dispatch({ type: actions.FETCH_FORM_DATA_SUCCESS, payload: formData })
      .catch(error => {
        // on error, do whatever is best for your use case
        dispatch({ type: actions.FETCH_FORM_DATA_ERROR, payload: error })

// reducer

  formData: {},
  error: {},
  fetching: false

export default function(state = INITIAL_STATE, action) {
  switch(action.type) {
      // when dispatch the 'request' action, toggle fetching to true
      return Object.assign({}, state, { fetching: true })
      return Object.assign({}, state, {
        fetching: false,
        formData: action.payload
      return Object.assign({}, state, {
        fetching: false,
        error: action.payload

// route can look something like this to access the formId in the URL if you want
// I use this URL param in the component below but you can access this ID anyway you want:
<Route path="/myForm/:formId" component={SomeForm} />

// form component
class SomeForm extends Component {
  componentWillMount() {
    // get formId from route params
    const formId = this.props.params.formId

  // in render just check if the fetching process is happening to know when to display the spinner
  // this could also be abstracted out into another method and run like so: {}
  render() {
    return (
      <div className="some-form">
        {this.props.fetching ? 
          <img src="./assets/spinner.gif" alt="loading spinner" /> :
          <FormComponent formData={this.props.formData} />

function mapStateToProps(state) {
  return {
    fetching: state.form.fetching,
    formData: state.form.formData,
    error: state.form.error

export default connect(mapStateToProps, { fetchFormData })(SomeForm)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download