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

Instagram Extends Reels Duration to 3 Minutes

Regardless of whether TikTok faces a U.S. ban, Instagram is wasting no time positioning itself…

2 days ago

AWS Expands Payment Options for Nigerian Customers, Introducing Naira (NGN) for Local Transactions

Amazon Web Services (AWS) continues to enhance its customer experience by offering more flexible payment…

6 days ago

Why JavaScript Remains Dominant in 2025

JavaScript, often hailed as the "language of the web," continues to dominate the programming landscape…

7 days ago

Amazon Moves to Upgrade Alexa with Generative AI Technology

Amazon is accelerating efforts to reinvent Alexa as a generative AI-powered “agent” capable of performing…

1 week ago

Smuggled Starlink Devices Allegedly Used to Bypass India’s Internet Shutdown

SpaceX's satellite-based Starlink, which is currently unlicensed for use in India, is reportedly being utilized…

1 week ago

Why Netflix Dumped React For its Frontend

Netflix, a pioneer in the streaming industry, has always been at the forefront of adopting…

1 week ago