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

Leave a Reply

Your email address will not be published. Required fields are marked *