I want to redirect when the sign up is failed in react.
And I am using Mobx.
So there is a question about this.
When I search for redirect, the people says that use the below code.

this.props.history.push("/");

this works when it is in the his own component.
But in my case, i am running that inside of action of mobx store.
And then, this.props is not the props of routes component.
So I wonder how I can read history of route through mobx store.
Thank you so much!

// In the mobx store

 @action submitSignIn = () => {
    axios
      .post('auth/join', { email: this.initialState.register.email })
      .then((response) => {
        if (response.data === true) {
          this.props.history.push('/signin');
        }
      .catch((error) => {
        console.log(error);
      });
  };

1 Answers

1
Tholle On Best Solutions

One way of going about it is to manually create a history object with the createBrowserHistory function from the history library, and give this object to the history prop of the Router component.

Then you can use this history object wherever you like in your app to programmatically control the routing.

Example

import { createBrowserHistory } from "history";
import { Router } from "react-router-dom";

const history = createBrowserHistory();

class Store {
  // ...

  @action submitSignIn = () => {
    axios
      .post("auth/join", { email: this.initialState.register.email })
      .then(response => {
        if (response.data === true) {
          history.push("/signin");
        }
      })
      .catch(error => {
        console.log(error);
      });
  };
}

ReactDOM.render(
  <Router history={history}>
    <App />
  </Router>,
  document.getElementById("app")
);