0

I have been attempting to Redirect upon user login. The login works correctly with my database and will conditionally render my new links for my admin portal. I was trying to use Redirect upon getting a status code 200, but I am not sure if this is even the correct way.

axios post for Login component:

const handleSubmit = e => {
    e.preventDefault();
    console.log(adminLogin)

    axios
      .post("/api/Authentication", adminLogin)
      .then(function(response) {
        if (response.status === 200) {
          setIsLoggedIn(true);
          <Redirect to="/inventory" />
        }
        setAdminLogin(response.data);
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });

3 Answers 3

1

You can't Redirect from function directly. If you want to redirect from function then you can use this.props.history.push('/inventory');

And another way to redirect using state.

const[login,setIsLoggedIn]=useState(false)

if (response.status === 200) {
       setIsLoggedIn(true);
}
if(login){
       return <Redirect to='/inventory'/>
}

return(
       //Main function return
);
Sign up to request clarification or add additional context in comments.

Comments

0

if you use react-router-dom you can see this example from documentation and you can see similiar question in here

Comments

0

As it is an axios call, it is always recommended to use this.props.history.push().

Make sure while using this function, you have already used withRouter to route your component.

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import axios from 'axios';

class App extends Component {
    ...
    const handleSubmit = e => {
    e.preventDefault();
    console.log(adminLogin)

    axios
      .post("/api/Authentication", adminLogin)
      .then(function(response) {
        if (response.status === 200) {
          setIsLoggedIn(true);
          this.props.history.push('/inventory');
        }
        setAdminLogin(response.data);
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });
    }
    ...
}

export default withRouter(App);

If you won't wrap your component with withRouter, history object will not be present in this.props and hence, will be throwing an error.

Comments

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.