6

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 Answer 1

12

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    
  }
Sign up to request clarification or add additional context in comments.

5 Comments

hello, yes sure, perfect i will try
axios.post must be in a function ? or it can be in the component like you did
In a function. Where do you have it now? Just leave it at the same place
I have in in my function postData which is called with onChange on my form
Sure, there's no need to change that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.