React-router: redirect from redux action in react router v4[Question]

Created on 3 Dec 2016  路  7Comments  路  Source: ReactTraining/react-router

I have used react-router v4 for routing in my application. In homepage, there is a form. When user fills up form and hits the submit button, then the action is dispatched(showResultofCar) and it should be redirected to result page which is not a child in the homepage instead it is a different page with different UI from top to bottom.

I tried to do this way but the action is not dispatched only the routing has been transitioned but shows the same homepage instead of new page(result)

**index.js**

    ReactDOM.render(
      <Provider store={createStoreWithMiddleware(reducers)}>
        <ConnectedIntlProvider>
          <Router>
            <App />
          </Router>
        </ConnectedIntlProvider>
      </Provider>
      , document.querySelector('.app'));


**app.js**

    render() {
      return (
          <div className="container-fluid">
            <Nav
              showModal={(e) => this.showModal(e)}
              hideModal={() => this.hideModal()}
              show={this.state.show}
              onHide={() => this.hideModal()}
            />
              <Banner />
              <Media />
              <Footer />
            </div>
            );
    }


**form.js(it is a child component of banner which is a child component of app)**

    onSubmit = (e) => {
      e.preventDefault();
      const originwithCountry = e.target.Origen.value;
      const originwithCity = originwithCountry.split(', ')[0];
      const cityFrom = base64.encode(originwithCity);
      const startDate = (new Date(e.target.startDate.value).getTime() / 1000);
      this.props.showResultofCar(cityFrom, cityTo, startDate);
      this.context.router.transitionTo('/result');
      }

    render() {
      const { focusedInput } = this.state;
      const { intl } = this.props;
      return (
        <div className="form-box text-center">
          <div className="container">
            <form className="form-inline" onSubmit={this.onSubmit}>
              <div className="form-group">
                <Field
                  name='Origen'
                  component={renderGeoSuggestField}
                />
              </div>
              <div className="form-group">
                <Field
                  name="daterange"
                  onFocusChange={this.onFocusChange}
                />
              </div>
              <Link to="/result">
              <button type="submit" className="btn btn-default buscar">
                { intl.formatMessage({ id: 'buscar.text' })}
              </button>
            </Link>
            </form>
          </div>
        </div>
      );
    }

**result-parent.js**

    class ResultParent extends Component {
      render() {
        return (
          <div className="result-page">
            <Match pattern='/result' component={Result} />
          </div>
        );
      }
    }

**result.js**

    class Result extends Component {
    render() {
      return (
        <div className="result-page">
          <ResultNav />
          <Filtering />
          <Results />
        </div>
      );
    }
    }

**actions/index.js**

    export function showResultofCar(cityFrom, cityTo, date) {
      return (dispatch) => {
        dispatch({ type: 'CAR_FETCH_START' });
        const token = localStorage.getItem('token');
        console.log('date', date);
        return axios.get(`${API_URL}/car/{"cityFrom":"${cityFrom}","cityTo":"${cityTo}","date":${date}}.json/null/${token}`)
          .then((response) => {
            console.log('response is', response);
            dispatch({ type: 'CAR_FETCH_SUCCESS', payload: response.data });
          })
          .catch((err) => {
            dispatch({ type: 'CAR_FETCH_FAILURE', payload: err });
          });
      };
    }

My way is not working. How can i now redirect using react router v4 inside action?

Also i don't want the result to be shown inside App component(parent) because result page will be completely different with its own navbar,filtering and results option.

Most helpful comment

Are there any examples of how to do this? I haven't had much luck. In my situation, I rely on forms for navigating a website, not just links.

I don't think using context is an appropriate option. Facebook certainly doesn't recommend it. "If you want your application to be stable, don't use context."

All 7 comments

Have your App component grab the router off of context and make it available in your store somehow. Best bet is using a middleware to intercept those kinds of actions.

Are there any examples of how to do this? I haven't had much luck. In my situation, I rely on forms for navigating a website, not just links.

I don't think using context is an appropriate option. Facebook certainly doesn't recommend it. "If you want your application to be stable, don't use context."

I'm in the same boat. I need to push a new route to history inside my redux actions. What do we do about this? It was so much easier with Router v3. :/

I found the answer:

https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux

Worked perfect for me. With a Redux action, just use dispatch(push('path'));

@chbrules I also get trouble, I use react-router-redux, but push can not work in action, url can change ,but component not.
When I use store.dispatch(push('path')) in store.js, it works. but in action.js, it can not work.

@yujiayinshi Did you include 'push' in your action.js?

import { push } from 'react-router-redux'

Also, you have to setup a reducer for it in your root reducer:

import { routerReducer } from 'react-router-redux'

const rootReducer = combineReducers({
    router: routerReducer,
    other reducers...
});
export default rootReducer;

@MilanRgm Did you ever find a suitable solution for this matter? I have now encountered the problem and tried @chbrules proposed solution to no avail.

"react-router-dom": "^4.1.2"
"react-router-redux": "4.0.8"
Was this page helpful?
0 / 5 - 0 ratings

Related issues

misterwilliam picture misterwilliam  路  3Comments

winkler1 picture winkler1  路  3Comments

yormi picture yormi  路  3Comments

wzup picture wzup  路  3Comments

ryansobol picture ryansobol  路  3Comments