Home > OS >  React login validating users from api with axios
React login validating users from api with axios

Time:04-27

i'm trying to make a login using axios to get data from an api, and if the user and passwors is found enter the app.

the code of login function is this:

loginSesion= async ()=>{
   var usu =this.state.form.username;
   var pas = this.state.form.username;
    
    await axios.get(baseUrl, {params: {user_name: this.state.form.username, user_password: this.state.form.password}})
    .then(response=>{
        return response.data;
    })
    .then(response=>{
        if(response.length>0){
            localStorage.setItem('user', this.state.form.username);
            localStorage.setItem('pass', this.state.form.password);
            window.location.reload();
        }else{
            alert('usuario o contraseña incorrecto')
        }
    })
    .catch(error=>{
        console.log(error);
    })
}

in this part of the code axios gets the params from the API and if the user_name/_password exist in the api returns the data.

await axios.get(baseUrl, {params: {user_name: this.state.form.username, user_password: this.state.form.password}})
    .then(response=>{
        return response.data;})

And if the response lenght is diferent of 0, it means that the data/user was found and set the user and password on localstorage to login the user:

.then(response=>{
    if(response.length>0){
        localStorage.setItem('user', this.state.form.username);
        localStorage.setItem('pass', this.state.form.password);
        window.location.reload();
    }else{
        alert('username or password not found')
    }

console log img

but i got stuck here, sometimes the axios.get loads with the object and somethimes it fails, as this is my first time using react and axios I don't know if this is the best way to validate if the user exists in the api and if it matches to start the sesion.

CodePudding user response:

I suggest you to take a look at some tutorial about reactjs first.

But here is a short video about authentication with axios and react.

you will learn a lot watching this video on youtube: https://www.youtube.com/watch?v=X3qyxo_UTR4

CodePudding user response:

I suggest my repository on my github. You can look at that. My repository is about react js and sprıng boot and security. there is 2 project about login auth...

https://github.com/celalaygar/SpringBoot-Security-JWT-React

  • Related