Hello everyone welcome into my new Article on React Native User Authentication. In this article, we are going to start from where we left on my previous article
React Native Login Screen Tutorial.
As requested by a user from my instagram account. I will add a simple user authentication workflow to the login screen.

User Authentication Concept

The concept of this workflow will be pretty simple.
The login screen will check for users’ email and password in the local storage using AsyncStorage API.
You can use tokens instead, it’s the same.
if so the app will continue to login the user.
if not the user needs to write down his Authentication details, call the authentication API.
And save the user data in the local storage.

UI Concept

For the UI, I will be using the same project from my previous article React Native Login Screen Tutorial.
You can check it to get the starting code or follow along if you want to.
Anyway, this is the Screen we will be working on

React Native user Authentication final result

Login Api

For this article I am going to use a Login Api from a real project I have been working on.
Where it requires the user to authenticate using an email an a password to access data.

The Login Api uses Nodejs Express and mongodb authentication.
If you guys want it I can put it on github or even make a tutorial on how to make user authentication using these technologies.

React Native Asyncstorage

First let’s start by importing react Native AsyncStorage.

If you haven’t used React Native AsyncStorage, it’s actually pretty similar to local storage in HTMl and Javascript.
You can store primary variable types in key pair values, and retrieve them at your will.

Asyncstorage Getitem

To get items from Local storage you use Asyncstorage getitem function.
It’s an async function, so you might need to include it within and async function to use it.
It takes one argument the string name of the item you want to retrieve.
Here is an example of Asyncstorage getitem

const email = await AsyncStorage.getItem("email")

Asyncstorage Setitem

To save data into the local storage you use Asyncstorage getitem function.
Similar to GetItem, you need to include it within an async function.
It takes two arguments the name and value of the item you want to save to Local storage.

Here is an example of Asyncstorage getitem

await AsyncStorage.setItem("email","email@reactnativemaster.com")

Let’s Get Started

Now you are ready to start the user authentication process.

Let’s start by the state to hold the the email, password, Loading indicator and a message for errors.
Our initial state will look like this.

    state={
        email:"",
        password:"",
        loading:false,
        message:""
    }

Next let’s have a function to check for the existing user in local storage.

    login=async ()=>{
        const email = await AsyncStorage.getItem("email")
        const password = await AsyncStorage.getItem("password")
        if(email && password){
            this.setState({email,password})
            this.authenticate(email, password)

        }
    }

As you see, it checks for the user email and password in the local storage and calls the authenticate function .
And updates the state with the new findings.

We will call this Function first when our the component mounts.

    componentDidMount(){
        this.login()
    }

Next is the authenticate function.

    authenticate=(email, password)=>{
        this.setState({loading:true,message:""})
        axios.get(`https://reactnativemaster.com/api/authenticate?email=${email}&password=${password}`)
        .then(async res=>{
            this.setState({loading:false})
            if(res.data.user_info.status==="Active"){
                await AsyncStorage.setItem("email",email)
                await AsyncStorage.setItem("password",password)
                this.props.navigation.navigate("Home")


            }else {
                this.setState({message:"This account is not active",loading:false})

            }
        })
        .catch(err=>{
            this.setState({message:"Error connecting to the server, Please try again later.",loading:false})

        })
    }

As you can see I am using Axios library to handle the API fetching.

The login api is is a GET method that requires an email and password.
Before it starts fetching, the function sets up the state with a loading indicator and removes previous messages.
Once the function gets the data, it checks user status wether active or not.
If the User is active, it will save his email and password back in the local storage using Asyncstorage.
And navigate the user to the Home screen.
If the user is not active it will update the state to display the message “This account is not active”.
However, if there was an issue like connection or something wrong with the server it will display this message “Error connecting to the server, Please try again later.”
By every state update, we stop the loading by setting it into false.

Now the last step is to add the authenticate method to the Login button in the screen. We could go even further and organize it into a React Native Stateful component, but for the sack of simplicity I will leave it as it is.

                <Button rounded style={styles.loginBtn} disabled={loading} onPress={()=>this.authenticate(email,password)}>
                    {
                        loading ? <Spinner  color="white"/>
                        :
                        <Text style={{color:"#fff"}}>LOGIN</Text>

                    }
                </Button>

And there you have it React Native User Authentication.
Simple and easy.
If you have requests to add more to the Login screen, feel free to comment it, and I will work on it right away.
Meanwhile, take care.
Happy Coding