react native

React Native: Make a POST Request With Axios And Reqres API

When working with React Native applications, you will often want to make API requests and calls either for Login, Registration or perhaps you might just want to retrieve and list out items from a database.

In this tutorial we shall be making a POST request in React Native using Axios and Reqres API.

API is the acronym for Application Programming Interface. It is a software intermediary that allows two applications to talk to each other usually from a single database.

A REST API allows you to push and pull (or retrieve) data from a database without you needing the database credentials. We have already talked extensively on REST APIs here.

Let us see how we can create a registration form and submit the data to an API using Axios.

What is Axios?

According to their website, “Axios is a promise-based HTTP Client for node.js and the browser“. It is based on the XMLHttpRequest interface provided by browsers. Good thing is we can also use Axios to make API calls in our React Native application.

In this demonstration, we shall be using Reqres to make our React Native API request. Reqres helps you test your frontend on a real API. It gives you fake and helps you develop with real response codes, GET, POST, PUT & DELETE all included.

Make React Native API Requests

First, let us create the form input with just basic styling.

render(){
 const {email, password, loading} = this.state;
return(                     
 <Input
  autoCapitalize="none"
  autoCorrect={false}
  returnKeyType="next"
  onChangeText={(value) => this.onChangeHandle('username', value)} />
 
 <Input
  secureTextEntry={this.state.hidePassword}
  autoCapitalize="none"
  autoCorrect={false}
  returnKeyType="next"
  onChangeText={(value) => this.onChangeHandle('password',   value)} />

 <TouchableOpacity 
  style={{
  ...styles.btn,
  backgroundColor: loading ? '#ddd' : '#A40606',
  }}
  onPress={() => this.doRegister()} >

 <Text style={styles.loginText}> 
 {loading ? 'Loading ...' : 'Click Here to Register'}
 </Text>
 </TouchableOpacity>
)
}

const styles = StyleSheet.create({
      btn: {
      alignSelf: 'stretch',
      alignItems: 'center',
      padding: 20,
      marginTop: 20,
      borderRadius: 25,
      backgroundColor: '#A40606',
    },
   loginText: {
      color: '#333',
      fontSize: 17,
      fontWeight: 'bold',
      textTransform: 'uppercase',
    },
});

Next, we need to listen for input change. So we will create a function that does that. But in order to do that, we first need to create our state variables like so:

constructor(props){
super(props);
this.state = {
email: '',
password: '',
loading: false
}
}

 onChangeHandle(state, value) {
    this.setState({
      [state]: value,
    });
  }

Moving forward, we then have to create the function that will handle our form registration.

        doRegister() {
          const {email, password} = this.state;
          if (email && password) {

            const req = {
              email: email,
              password: password,
            };

            this.setState({
              loading: true,
            });

            axios.post('https://reqres.in/api/register', req).then(
              (response) => {
                this.setState({
                  loading: false,
                });

                if (response.status === 200) {
                   Alert.alert("Registration successful", response.message);
                   //do something

                } else {
                  alert('An error occurred. Please try again later.');
                }

              },

              (err) => {
                this.setState({
                  loading: false,
                });

                Alert.alert('Could not establish connection',err.message);
              },

            );

          } else {
            alert('Please complete registration');
          }
        }

This is the response that you should get from the Reqres API and you should also use these values for the email and password fields.

Full code for our React Native API request:

import React, {Component} from 'react';
import {
  View,
  Text,
  KeyboardAvoidingView,
  TouchableOpacity,
  Alert,
  StyleSheet,
} from 'react-native';
import axios from 'axios';

class Register extends Component {
 
constructor(props){
super(props);
this.state = {
email: '',
password: '',
loading: false
}
}

 onChangeHandle(state, value) {
    this.setState({
      [state]: value,
    });
  }

    doRegister() {
          const {email, password} = this.state;
          if (email && password) {

            const req = {
              email: email,
              password: password,
            };

            this.setState({
              loading: true,
            });

            axios.post('https://reqres.in/api/register', req).then(
              (response) => {
                this.setState({
                  loading: false,
                });

                if (response.status === 200) {
                   Alert.alert("Registration successful", response.message);
                   //do something

                } else {
                  alert('An error occurred. Please try again later.');
                }

              },

              (err) => {
                this.setState({
                  loading: false,
                });

                Alert.alert('Could not establish connection',err.message);
              },

            );

          } else {
            alert('Please complete registration');
          }
        }


 render(){
 const {email, password, loading} = this.state;
return(
<View>
<KeyboardAvoidingView style={styles.wrapper}>                     
 <Input
  autoCapitalize="none"
  autoCorrect={false}
  returnKeyType="next"
  onChangeText={(value) => this.onChangeHandle('username', value)} />
 
 <Input
  secureTextEntry={this.state.hidePassword}
  autoCapitalize="none"
  autoCorrect={false}
  returnKeyType="next"
  onChangeText={(value) => this.onChangeHandle('password',   value)} />

 <TouchableOpacity 
  style={{
  ...styles.btn,
  backgroundColor: loading ? '#ddd' : '#A40606',
  }}
  onPress={() => this.doRegister()} >

 <Text style={styles.loginText}> 
 {loading ? 'Loading ...' : 'Click Here to Register'}
 </Text>
 </TouchableOpacity>
</KeyboardAvoidingView>
</View>
)
}
}

const styles = StyleSheet.create({
      btn: {
      alignSelf: 'stretch',
      alignItems: 'center',
      padding: 20,
      marginTop: 20,
      borderRadius: 25,
      backgroundColor: '#A40606',
    },
   loginText: {
      color: '#333',
      fontSize: 17,
      fontWeight: 'bold',
      textTransform: 'uppercase',
    },
});

export default Register;

Download free mobile app templates for your personal and school projects

Recent Posts

Service Workers in JavaScript: An In-Depth Guide

Service Workers are one of the core features of modern web applications, offering powerful capabilities…

2 weeks ago

What are Database Driven Websites?

A database-driven website is a dynamic site that utilizes a database to store and manage…

2 weeks ago

How to show Toast Messages in React

Toasts are user interface elements commonly used in software applications, especially in mobile app development…

2 weeks ago

Exploring the Relationship Between JavaScript and Node.js

JavaScript has long been synonymous with frontend web development, powering interactive and dynamic user interfaces…

3 weeks ago

Key Differences Between Tailwind CSS and CSS3

Introduction: In the world of web development, CSS (Cascading Style Sheets) plays a crucial role…

4 weeks ago

Why Everybody is Learning JavaScript Right Now

JavaScript has emerged as a ubiquitous programming language, powering the modern web and extending its…

4 weeks ago