2

I'm using React + Redux + React Router for an app. My initial page is a login screen and once authentication is successful, would like to redirect to another page while passing the token retrieved from authentication. I'm looking at this SO question but does not show how to pass a value into the new page: React Router Redirect

I'm thinking of taking Dan's advice of sticking the redirect in the action creator (for a successful login) but just not sure how to pass the token back as well. This is my action creator:

export const loginSucceeded = token => {
    browserHistory.push('/dashboard')
}
Community
  • 1
  • 1
Los Morales
  • 1,623
  • 4
  • 20
  • 34
  • I would suggest storing the token in `localStorage`. Then it will be accessible anywhere and will remain after a page refresh. – azium Aug 12 '16 at 20:16
  • But you can of course create a reducer for your token, and access it via `connect` – azium Aug 12 '16 at 20:17
  • @azium Isn't it better to save in `localStorage` to handle page refresh? If the `localStorage` token is empty, then request for auth. Yes, it has to be using a reducer too and everywhere else access the token via reducer. So it may be a combination of your two comments :) – anoop Aug 13 '16 at 01:06

2 Answers2

0

I would suggest using react-router-redux. It comes with push and replace actions so you can dispatch them in loginSucceeded action creator. It's a cleaner way to handle route changes and you'll see proper actions in redux dev tools. And it's a good idea to store a token in localStorage

Assuming you use redux-thunk middleware:

export const loginSucceeded = token => {
  return dispatch => {
    localStorage.setItem('token', token);
    dispatch(push('/dashboard'));
  };
};
Dmitriy Nevzorov
  • 5,697
  • 1
  • 18
  • 28
0

With react-router 4 you can try this:

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

export const loginSucceeded = token => {
    <Redirect push to={{
        pathname: '/dashboard',
        state: { token: token }
    }}/>
}

Later this token can be accessed via this.props.location.state.token from dashboard page.

More about here

Shibbir Ahmed
  • 1,327
  • 14
  • 19