Redirection using Axios and React

Viewed 16448

I have a little problem with Axios and I don't know how to redirect after a signup or a login.

Here is my code:

axios.post("/api/user/signup", { data })
  .then(res => {
    if (res.status === 200) {
      console.log("REDIRECTION avec status => ", res.status);
      // how to redirect here
      <Redirect to = {{ pathname: "/home" }} />
    }

The flow reaches the console.log call but I can't find how to redirect after it in React.

1 Answers

Based on your usage of the Redirect component, I assume you are using React Router as the routing-logic library.

React Router (v4) handles routing at rendering time.

This means that redirection will happen when the Redirect component is rendered.

One way to control this is by leveraging the state.

In React, changing the state causes a re-rerender.

Here's one approach:

class MyComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isSignedUp: false // <-- initialize the signup state as false
    }
  }

  signup() {
    return axios.post("/api/user/signup", { data })
      .then(res => {
        if (res.status === 200) {
          this.setState({ isSignedUp: true }); // after signing up, set the state to true. This will trigger a re-render
        }
  }

  // ...

  render() {
    if (this.state.isSignedUp) {
      // redirect to home if signed up
      return <Redirect to = {{ pathname: "/home" }} />;
    }

    // ... rest of rendering code    
  }
Related