S
S
Sergey Alekseev2018-03-14 14:03:32
React
Sergey Alekseev, 2018-03-14 14:03:32

React + Redux, how to redirect user after successful network request?

Good afternoon, I am doing authorization and after receiving the token from the backend, do I need to redirect the user to his page?

createAction

export const login = (username, password) => {
    return dispatch => {


        axios.post("http://127.0.0.1:8000/login/", {
            username: username,
            password: password
        })
            .then(function (res) {
                dispatch(loginSuccess(res.data.token));
                dispatch(push("/home"))
            })
            .catch(function (error) {
                if (error.response.status === 400) {
                    dispatch(loginError())
                }
            });
    }
};

store

import { createStore, applyMiddleware } from "redux";
import thunkMiddleware from "redux-thunk";
import { createLogger } from "redux-logger";
import rootReducer from "../Reducers/index";
 
const loggerMiddleware = createLogger();
 
export default function store() {
  return createStore(
    rootReducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
    applyMiddleware(
      thunkMiddleware,
      loggerMiddleware
    )
  )
}

React render
const history = createBrowserHistory();
const Store = store(history);


render(
  <Provider store={Store}>
        <div className="root_container">
            <ConnectedRouter history={history}>
                <Switch>
                    <Route exact path={"/"} component={Welcome} />
                    <Route exact path={"/login"} component={LoginContainer} />
                    <Route exact path={"/register"} component={RegisterContainer} />
                    <Route exact path={"/home"} component={AppContainer} />
                </Switch>
            </ConnectedRouter>
        </div>
    </Provider>,
    document.getElementById("root")
);

I saw a variant with dispatch.push("/home"), but it only fires the action and does not redirect

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2018-03-14
@miraage

Add routerMiddleware(history)to applyMiddlewarewhen creating store.

R
Roman Aleksandrovich, 2018-03-14
@RomReed

I think that here is a great answer to your question
https://stackoverflow.com/questions/45089386/what-...
you can also try this package
https://www.npmjs.com/package/react-redirect

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question