DDecoene
DDecoene

Reputation: 7280

Where do I update the location after an async dispatch with react-router and redux

The problem I have now is that I don't know how to get my location to update after "FETCH_USER_FULFILLED" was dispatched (see https://github.com/DDecoene/React-flux-example/blob/4ab1503dc92d28108f50481a293104ba5d15a29e/app/actions/userActions.js#L17)

What I'm trying to do, is to do a post to an API and when it is OK, switch to the index 'page'

I've tried redux-router too but I did not get it to work at all.

Upvotes: 0

Views: 256

Answers (2)

Jakub Kłobus
Jakub Kłobus

Reputation: 31

probably the simplest solution is to use browserHistory.push() after dispatch:

import { browserHistory } from 'react-router';

...

axios.post(Endpoints.userLogin, {username, password})
  .then((response) => {
      dispatch({type: "FETCH_USER_FULFILLED", payload: response.data});
      browserHistory.push('your/index/route');

  })

Upvotes: 0

Dmitriy Nevzorov
Dmitriy Nevzorov

Reputation: 6078

I would suggest using react-router-redux. It comes with push and replace actions so you can dispatch them in your action creator. It's a cleaner way to handle route changes and you'll see proper actions in redux dev tools. Assuming you use redux-thunk middleware:

export const fetchUser = (username, password) => {
  return dispatch => {
    axios.post(Endpoints.userLogin, {username, password}).then((response) => {
      dispatch({type: "FETCH_USER_FULFILLED", payload: response.data});
      dispatch(push('/new_location'));
    });
  };
};

Upvotes: 1

Related Questions