javascriptreactjsreact-routerreact-loadable

How to redirect login page to dashboard using ReactJS?


I want when I submit the email and the password to login, it will be redirected to the dashboard, my code is below :

     handleClick(event){
    
    var payload={
      "email":this.state.email,
        "password":this.state.password
    }
    axios({
          method: 'post',
          url: '/app/login/',
          data: payload,
          withCredentials: true,
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
            'Accept': 'application/json',
          }
        })
   
   .then(function (response) {
     console.log(response);
     if(response.data.code == 200){
          response.redirect('http://localhost:5000/#/dashboard');

     }
     else if(response.data.code == 204){
       swal("Erreur !", "Vérifiez vos champs SVP !", "error");
      
     }
     else{
       swal("Erreur !", "Username inexistant !", "error");
      
     }
   })
  }

My route :

import React from 'react';
import Loadable from 'react-loadable'
const Dashboard = Loadable({
  loader: () =>
    import ('./views/Dashboard'),
  loading: Loading,
});
const routes = [
{ path: '/dashboard', name: 'Dashboard', component: Dashboard }]

When I run it, I get : enter image description here

How can I fix that please ?


Solution

  • There is no redirect method in axios response object. To handle this you might workout with your router which you use.

    Example:

    router.push({ path: '/dashboard' }) Like this...

    Edited:

    In case you using react-router: try to extract history from component props, like this:

    this.props.history.push('/dashboard')