Django and React: how to redirect to main page after successful login

Viewed 20

I am building a login system webapp using react + django. My question is how can I redirect a user towards the main page, if the login credentials are successful.

Right now I only managed to retrieve the authentication token from the backend. How can I modify this class to also check if the login is successful and then redirect towards the main page?

class Login extends Component {


  state = {
    credentials: {username: '', password: ''}
  }

  login = event => {
    fetch('http://127.0.0.1:8000/auth/', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(this.state.credentials)
    })
    .then( data => data.json())
    .then(
      data => {
        this.props.userLogin(data.token);
      }
    )
    .catch( error => console.error(error))
  }

  register = event => {
    fetch('http://127.0.0.1:8000/api/users/', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(this.state.credentials)
    })
    .then( data => data.json())
    .then(
      data => {
        console.log(data.token);
      }
    )
    .catch( error => console.error(error))
  }
  inputChanged = event => {
    const cred = this.state.credentials;
    cred[event.target.name] = event.target.value;
    this.setState({credentials: cred});
  }

  render() {
    return (
      <div>
        <h1>Login user form</h1>

        <label>
          Username:
          <input type="text" name="username"
           value={this.state.credentials.username}
           onChange={this.inputChanged}/>
        </label>
        <br/>
        <label>
          Password:
          <input type="password" name="password"
           value={this.state.credentials.password}
           onChange={this.inputChanged} />
        </label>
        <br/>
        <button onClick={this.login}>Login</button>
        <button onClick={this.register}>Register</button>
      </div>
    );
  }
}
1 Answers

you need to use hook in react dom router :

please check out this answer , to get more help :

react router doom

but for you id React-Router v6 you can do the following:


import { useNavigate } from "react-router-dom";

navigateIfSuccess() {
  let navigate = useNavigate();
  // Somewhere in your code, e.g. inside a handler:
  navigate("/your-home-page"); 
}

and in then response you can check if token ? then you can call this function :

like this :


  .then(
      data => {
        if (token)
          {
           navigateIfSuccess()
          }
      }
Related