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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With