Home > Enterprise >  How to display an Error message when logging in fails in Reactjs
How to display an Error message when logging in fails in Reactjs

Time:03-18

How to display an Error message when logging in fails in Reactjs. I want to display the alert message 'Invalid Username or Password, Please try again.' when the user logs in fails on the page. How can I do that in Reactjs?

the code:

    login.js
export default function LogIn() {
    let history = useHistory();
    const initialFormData = Object.freeze({
        username: '',
        password: '',
    });

const [formData, updateFormData] = useState(initialFormData);

const handleChange = (e) => {
    updateFormData({
        ...formData,
        [e.target.name]: e.target.value.trim(),
    });
};

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

    axiosInstance
        .post(`token/`, {
            username: formData.username,
            password: formData.password,
        })
        .then((res) => {
            localStorage.setItem('access_token', res.data.access);
            localStorage.setItem('refresh_token', res.data.refresh);
            axiosInstance.defaults.headers['Authorization'] =
                'JWT '   localStorage.getItem('access_token');
                history.push("/home");
            
        });
};
return (
    <Box component="form" onSubmit={handleSubmit} noValidate>
      <TextField
           margin="normal"
           required
           id="username"
           label="username"
           name="username"
           autoComplete="username"
           autoFocus
           onChange={handleChange}/>

      <TextField
        margin="normal"
        required
        name="password"
        label="password"
        type="password"
        id="password"
        autoComplete="current-password"
        onChange={handleChange}/>
                        
         <Button type="submit" onClick={handleSubmit}>
                 LOG IN
          </Button>            
          </Box>    
);}

Thank you in advance.

CodePudding user response:

you can use alert in javascript to show a dialog box also you can use this Pakage

to show alert or message to the user

you can use this code to set error in state and show in label

const [error,setError]=useState();
const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);

    axiosInstance
        .post(`token/`, {
            username: formData.username,
            password: formData.password,
        })
        .then((res) => {
            localStorage.setItem('access_token', res.data.access);
            localStorage.setItem('refresh_token', res.data.refresh);
            axiosInstance.defaults.headers['Authorization'] =
                'JWT '   localStorage.getItem('access_token');
                history.push("/home");
            
        }, reason => {
  console.error(reason); // Error!
setError('Invalid Username or Password')
});
};
return (
    <Box component="form" onSubmit={handleSubmit} noValidate>
      <TextField
           margin="normal"
           required
           id="username"
           label="username"
           name="username"
           autoComplete="username"
           autoFocus
           onChange={handleChange}/>

      <TextField
        margin="normal"
        required
        name="password"
        label="password"
        type="password"
        id="password"
        autoComplete="current-password"
        onChange={handleChange}/>
                        
         <Button type="submit" onClick={handleSubmit}>
                 LOG IN
          </Button>  
         {error?<Label>{error}</Label>:null}          
          </Box>    
);
  • Related