Search code examples
javascriptreactjsreact-routeraxiosreact-fullstack

Even if the axios response is true the page is not routing to Home?


I am getting the boolean output from the axios.reponse but i want to use this reponse to route to another page. But I am using form to give data so it can't come to the main return. So,could u please tell where should i write my route statement such that after getting correct username and password i can redirect to new page.

import withRoot from './modules/withRoot';
// --- Post bootstrap -----
import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Link from '@material-ui/core/Link';
import { FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import { Field } from 'react-final-form';
import Typography from './modules/components/Typography';
import AppFooter from './modules/views/AppFooter';
import AppAppBar from './modules/views/AppAppBar';
import Axios from 'axios';
import AppForm from './modules/views/AppForm';
import Button from '@material-ui/core/Button';
import { Alert } from 'reactstrap';
import { email, required } from './modules/form/validation';
import RFTextField from './modules/form/RFTextField';
import FormButton from './modules/form/FormButton';
import FormFeedback from './modules/form/FormFeedback';
import TextField from '@material-ui/core/TextField';
import Home from './Home';
import Dashb from './Dashb';



const useStyles = makeStyles((theme) => ({
  form: {
    marginTop: theme.spacing(6),
  },
  button: {
    marginTop: theme.spacing(3),
    marginBottom: theme.spacing(2),
  },
  feedback: {
    marginTop: theme.spacing(2),
  },
}));
    
               export default function SignIn() {
               const [username, setUsername] = useState("");
               const [password, setPassword] = useState("");
               const [status, setStatus] = useState(true);
               const classes = useStyles();
               let demo;
               function validateForm() {
                   return username.length > 0 && password.length > 0;
                 }
        
          function setIncorrect() {
            setStatus(false);
          }
        
        
        
          function setCorrect() {
            setStatus(true);
          }
        
        
          async function handleSubmit(event) {
            event.preventDefault();
        
        let user = await Axios.get('http://localhost:9000/admin-service/admin/check/' + username + '/' +          password).then(
              (response) => {
                demo = response.data;
              }).catch(
                (error) => {
                  console.log(error.response.data);
                  setIncorrect();
                }
              )
        
            if (demo == true) {
              console.log("####");
              return (
                <Home />
              )
        
            }
            else {
              console.log("!!!!!");
            }
        
        
        
          }
        
          return (
            <React.Fragment>
              <AppAppBar />
              <AppForm>
                <React.Fragment>
                  <Typography variant="h3" gutterBottom marked="center" align="center">
                    Admin Sign In
                  </Typography>
                </React.Fragment>
        
                <form onSubmit={handleSubmit} className={classes.form} noValidate>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    required
                    fullWidth
                    id="username"
                    label="Username"
                    name="username"
                    autoFocus
                    onChange={e => { setUsername(e.target.value); setCorrect() }}
                  />
                  <TextField
                    variant="outlined"
                    margin="normal"
                    required
                    fullWidth
                    name="password"
                    label="Password"
                    type="password"
                    id="password"
                    autoComplete="current-password"
                    onChange={e => { setPassword(e.target.value); setCorrect() }}
                  />
                  {(!status) && <Alert severity="error">Incorrect credentials. Please try again</Alert>}
        
                  <FormButton
                    type="submit"
                    className={classes.button}
                    disabled={!validateForm()}
                    size="large"
                    color="secondary"
                    fullWidth
                  >
                    Sign In
                      </FormButton>
                </form>
        
        
                <Typography align="center">
                  <Link underline="always" href="/premium-themes/onepirate/forgot-password/">
                    Forgot password?
                  </Link>
                </Typography>
              </AppForm>
              <div>
                if  {
        
                }
              </div>
        
            </React.Fragment>
        
        
          );
        }

Solution

  • I would write it like so:

    async function handleSubmit(event) {
      event.preventDefault()
    
      let user = await Axios.get(
        'http://localhost:9000/admin-service/admin/check/' +
          username +
          '/' +
          password
      )
        .then(response => {
          demo = response.data
          if (demo == true) {
            console.log('####')
            history.push('/')
          } else console.log('not true')
        })
        .catch(error => {
          console.log(error.response.data)
          setIncorrect()
        })
    }
    

    instead of returning the component maybe do a history.push() using react-router-dom