H
H
hadaev_ivan2016-06-08 17:24:26
JavaScript
hadaev_ivan, 2016-06-08 17:24:26

React, redux, react-router, react-router-redux, how and where to redirect after login?

I just can not figure out where it is more correct to do a redirect after the user has successfully logged in. I thought that it would be more correct to do in action like this:

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

export function login(userData) {
    return dispatch => {
        dispatch(requestLogin());

        return fetchBlabla(user)
            .then((json) => {
                dispatch(successLogin(json));
                dispatch(push('/'));
            });
    }
}

but in this case the address bar changes but the content stays the same.
Store initialization code
import React from 'react';

import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import { routerReducer, routerMiddleware } from 'react-router-redux';
import thunkMiddleware from 'redux-thunk';
import * as reducers from './reducers';

export function configureStore(history, initialState) {

    const reducer = combineReducers({
        ...reducers,
        routing: routerReducer
    });

    const store = createStore(
        reducer,
        initialState,
        compose(
            applyMiddleware(
                thunkMiddleware,
                routerMiddleware(history)
            ),
            window.devToolsExtension ? window.devToolsExtension() : f => f
        )
    );

    return store;
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-06-08
@hadaev_ivan

Think correctly, dispatch REDIRECT should be done after dispatch SUCCESS_LOGIN.
Judging by the documentation , in action creators (the creator of the action, the first block of code), you are doing everything right.
Next, check for yourself (I will give a code similar to yours):
1) in the place where you pass history (usually this is the Root / App component, that is, the parent of everything)

import { AppContainer } from 'react-hot-loader'
import React from 'react'
import ReactDOM from 'react-dom'
import { Router, browserHistory } from 'react-router' // раз
import { Provider } from 'react-redux'
import { routes } from './routes'
import { syncHistoryWithStore } from 'react-router-redux' //два
import configureStore from './store/configureStore'

const store = configureStore()

const history = syncHistoryWithStore(browserHistory, store) //три
const rootEl = document.getElementById('root')

ReactDOM.render(
  <Provider store={store}>
    <AppContainer>
      <Router history={history} routes={routes} /> //четыре
    </AppContainer>
  </Provider>,
  rootEl
)

2) in the place where you configure the store object (usually, this is the configureStore function )
import { routerMiddleware } from 'react-router-redux' //раз
import { browserHistory } from 'react-router' //два
import { createStore, applyMiddleware, compose } from 'redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import { rootReducer } from '../reducers'

export default function configureStore() {
  const store = compose(
    applyMiddleware(thunkMiddleware),
    applyMiddleware(createLogger()),
    applyMiddleware(routerMiddleware(browserHistory)), //три (!)
  )(createStore)(rootReducer)

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers').rootReducer
      store.replaceReducer(nextRootReducer)
    });
  }

  return store
}

3) combineReducers with routing (as you wrote)
import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux' //раз
import products from './products'
import login from './login'
import notificationBar from './notificationBar'
import provider from './provider'

export const rootReducer = combineReducers({
  products,
  login,
  notificationBar,
  provider,
  routing: routerReducer, //два
})

There is not enough information from your question, but apparently you are either:
a) passing the wrong history to configureStore
b) not doing syncHistoryWithStore (from point 1)
--- additionally ---
Alternatively, see how to redirect after login in redux with middleware (simplified version, but good for understanding the basics)
There is also a "simple" option - to store the necessary data after login (token, user properties, etc.) in localStorage. And after login, do the standard browserHistory.push

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question