Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirection using Axios and React

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.

like image 444
jim2k Avatar asked Dec 23 '18 02:12

jim2k


People also ask

How do I redirect in Axios React?

To make redirects after an axios post request with Express and React, we set window. location to the new URL value after the response from the axios request to the Express back end is available. import React, { Component } from "react"; //... class MyClass extends Component { onSubmit = async (e) => { e.

How do I redirect in React?

The Redirect component was usually used in previous versions of the react-router-dom package to quickly do redirects by simply importing the component from react-router-dom and then making use of the component by providing the to prop, passing the page you desire to redirect to.

Can Axios be used in React?

In ReactJS, Axios is a library that serves to create HTTP requests that are present externally. It is evident from the fact that we may sometimes in React applications need to get data from the external source.


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    
  }
like image 63
nem035 Avatar answered Oct 22 '22 12:10

nem035