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

Common Async/Await Mistakes Every JavaScript Developer Should Avoid

JavaScript's async and await keywords revolutionized asynchronous programming by making asynchronous code look and behave more like synchronous code.…

3 hours ago

PGP Encryption And How It Works

Pretty Good Privacy (PGP) is one of the most widely used encryption systems for securing emails,…

4 days ago

How To Migrate from PostgreSQL to MySQL

Database migration is one of the most challenging tasks in software engineering. While both PostgreSQL…

1 week ago

Hidden Gems Inside Modern JavaScript

Modern JavaScript isn’t just let, const, arrow functions, and promises anymore. Over the years, the language has…

1 week ago

Software Developer Pain Points Ranked: What Frustrates Developers the Most?

Software development is one of the most rewarding careers in technology, but it is also…

1 week ago

How to Print Documents in JavaScript

Printing a document in JavaScript usually means triggering the browser’s print dialog and controlling what…

2 weeks ago