Table of Contents
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
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
Hello sir
I am a diploma student and i have learnt the design in react native.
But now i want to connect it to local database MySQL
Can you please help me getting it. …
You can use SQL database in react native in 2 ways.
Either by creating an API to connect to the MYSQL server and consume it.
Or by using SQLite to use the database locally (Offline)
love your work.,Sir can you aslo share your expo source code link. it will be very great
Thank you mate, I really appreciate it.
Here you go https://exp.host/@alhydra/react-native-login-screen-tutorial
You can help me show source code in github ? Thank sir. I’m from VietNam
Hi Sir,
The Github source code is already mentioned in the article.
can you share the full code of the user authentication?
Hey,
I have a problem with AsyncStorage its possible to have more details of ur code because it doesnt work on my project .
Best Regard
Adrien
Hi Adrien,
I am happy to help, what seems to be the problem ?
I have a problem with the asyncstorage. When i launch the application with expo, i have the error with asyncstorage and i dont understand why i have this error because i follow ur code.
What’s the error message you are getting ?
Do you have a repo set up for user authentication? For some reason adding additional fields to the state object results in
“Cannot find variable ‘loading'”
Yeah,
Here https://github.com/Alhydra/React-Native-Login-Screen-Tutorial
Hi,
I dont know why I am getting the error on the loading variable we defined in the state. I hope you could take a look at it.
here’s the screenshot: https://we.tl/t-p3JLVvmYri
Can you share the source code for authentication, as I am having issues with the loading component in the button. Thank you in advance
Here,
https://github.com/Alhydra/React-Native-Login-Screen-Tutorial
Thank you for your response, but the repository doesn’t include the authentication code. It would be great if you could help me with that. Thank you
Great tutorial. How is the asyncstorage items for email and password getting set? The article doesn’t mention this part.
Thank you sir, im beginner of react native, you ‘re acttualy save me
thank you sir
Thank you for your good blog as always.Have a great day today