Moses Esan
Aug 20 · 4 min read

Continuing from Part 1 and Part 2, the first module usually needed in a new app is the authentication module.

Demo

Authentication includes the ability to:

  1. Register
  2. Login
  3. Forgot Password — Will not be covered

Before continuing, make sure you have gone through the previous tutorials and created a sample module.

Follow Step 1 from Part 1 to create and set up the modules files and folders.

Make sure you are in the project root$ npm i --save react-native-material-textfield$ cd app/modules && mkdir auth && cd auth && mkdir components scenes && touch index.js constants.js api.js reducer.js utils.js

Step 1: Constants

In the constants file, declare the API endpoints, redux action types and two variables titled “TOKEN_KEY” and “USER_KEY”.

TOKEN_KEY: Used for storing and retrieving the access token from the local storage

USER_KEY: Used for storing and retrieving user data from the local storage.

The local storage is accessed using React Native Asyncstorage.

modules/auth/constants.js

Step 2: Create API

This functions declared in this file will interact with the backend API.

For this tutorial, I am using https://reqres.in/,

“Reqres simulates real application scenarios. If you want to test a user authentication system, Reqres will respond to a successful login/register request with a token for you to identify a sample user, or with a 403 forbidden response to an unsuccessful login/registration attempt. — -ReqRes

The constants file is imported, giving access to the previously declared constant variables.

register: accepts users data as parameters and returns a promise object. It’s callback function makes an API request to register the user, if successful, the promise is resolved with the data. If an error occurs, the promise is rejected with the error object.

The login function is similar to the register function but calls a different endpoint.

The handleError function is in charge of returning the appropriate error message.

modules/auth/api.js

Step 3: Create Reducer

The reducer will be responding to the “LOGGED_IN” and “LOGGED_OUT” actions.

LOGGED_IN
The reducer sets the isLoggedIn state variable to true and sets the user state variable.

LOGGED_OUT
The reducer sets the isLoggedIn state to false and sets the user state variable to null.

modules/auth/reducer.js

Root Reducer
Add the module reducer to the rootReducer.js file.

app/redux/rootReducer.js

Utils

getToken: Returns a promise, attempts to retrieve the access token and user data from the local storage using AsyncStorage multiGet function. If token exists, the promise is resolved with the token and the user data. If an error occurs, the promise is rejected.

setToken: Attempts to save the access token and user data in the local storage using AsyncStorage multiSet function. If successful, a new action with the type LOGGED_IN and the user data is dispatched to the reducer.

removeToken: Removes the access token and user data from the local storage using AsyncStorage multiRemove function. If successful, a new action with the type LOGGED_OUT is dispatched to the reducer.

checkLoginStatus: Calls the getToken function, If the token and user object is returned, a new action with the type LOGGED_IN and the user data is dispatched to the reducer.

Paste the code below in the utils.js file.

modules/auth/utils.js

Step 4: Create Components and Scenes

Components

Shared: Contains several components used in various scenes in this module.

Make sure you are in the project root$ cd app/modules/auth/components
$ mkdir Shared && cd Shared
$ touch index.js styles.js

Paste the code below in the index.js file.

modules/auth/components/Shared/index.js

Paste the code below in the styles.js file.

modules/auth/components/Shared/styles.js

Scenes

Make sure you are in the project root$ cd app/modules/auth/scenes
$ touch styles.js AuthLoading.js Register.js Login.js

AuthLoading: Renders the Expo AppLoading component. In the useEffect function, the checkLoginStatus function in the utils.js is called.

The checkLoginStatus returns a promise, if the promise is resolved, the app navigates to the App stack , if rejected, the app navigates to the Auth stack.

*modules/auth/scenes/AuthLoading.js

Register: This scene displays three text fields and one button. The onValidate functions validates the input and the onRegister function calls the register function in the api.js.

If registration is successful, the setToken function is called, if the token is successfully saved, the app navigates to the App stack. If the function returns an error, it is displayed to the user.

function onRegister() {
setLoading(true);

let data = {email, password};
register(data)
.then((data) => setToken(data.token, testUser))
.then(() => navigation.navigate('App'))
.catch((error) => setErrorMsg(error))
.finally(() => setLoading(false));
};
*modules/auth/scenes/Register.js

Login: This scene displays two text fields and one button. The onValidate functions validates the input and the onLogin function calls the login function in the api.js.

function onLogin() {
setLoading(true);

let data = {email, password};
login(data)
.then((data) => setToken(data.token, testUser))
.then(() => navigation.navigate('App'))
.catch((error) => setErrorMsg(error))
.finally(() => setLoading(false));
};
modules/auth/scenes/Login.js

Styles

modules/auth/scenes/styles.js

Module Index
The module index file is the entry point into the module, the module’s routes stack is created using React Navigation createStackNavigator function. The routes stack is created and exported along with the AuthLoading scene.

createStackNavigator: Provides a way for your app to transition between screens where each new screen is placed on top of a stack. — React Navigation

*modules/auth/index.js

Step 5: Update Apps Routes Stack

In the index.js file, the AuthLoading and the auth routes stack are imported and the main routes stack is updated.

*app/index.js

Run the command below to test the app.

$ expo start

Testing

Register

{
"email": "eve.holt@reqres.in",
"password": "pistol"
}

Login

{
"email": "eve.holt@reqres.in",
"password": "cityslicka"
}

In Part 4, a Movies module will be added.

That’s all folks!

Related Tutorials

  1. How to Build a React Native App Using React Hooks and Redux — Getting Started Boilerplate
  2. How to Build a React Native App Using React Hooks and Redux — Create “Modules”
  3. Tutorial 1: React Native Redux Boilerplate
  4. Tutorial 2: React Native Redux with CRUD operations

Other Tutorials

  1. Tutorial 4: How to Build a Laravel 5.4 JWT-Powered Mobile App Authentication API
  2. Tutorial 5: How to Build a Laravel 5.4 JWT Authentication API with E-Mail Verification
  3. Tutorial 6 & 7: How to Build a Laravel 5.4 Administration Module with Role-based permissions using Entrust package

Mesan Digital

Sharing tutorials on the development of React Native and PHP projects.

Moses Esan

Written by

Full Stack Developer

Mesan Digital

Sharing tutorials on the development of React Native and PHP projects.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade