1

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>
    );
  }
}
Orl13
  • 339
  • 4
  • 15
  • Try: `window.location` or [React Router](https://reactrouter.com) – Shri Hari L Sep 23 '22 at 12:44
  • [e.g here](https://css-tricks.com/react-router-4/) ... since its class components I have shared v4 version .... feel free to check docs for latest versions – KcH Sep 23 '22 at 12:48

1 Answers1

0

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()
          }
      }
Ahmad Akel Omar
  • 317
  • 2
  • 11