Working with APIs Calls In React Native

Introduction

In today's world of mobile app development, working with APIs is a fundamental requirement. APIs allow developers to integrate data from various sources and services into their apps. In this article, we'll explore how to work with APIs in React Native. So, without further ado, let's get started,

How to make a GET API call in React Native?

This module provides a simple interface for sending network queries and managing responses. We can use the built-in Fetch API library to make a GET/POST API call in a React Native application. To use it, simply pass a URL to the fetch method, which will return a Promise that resolves to a Response object. We can use this response object to manage the data given by the API call and alter the state of our application as needed.

The following code example shows a simple joke application that generates a random joke when clicking a button.

import { TouchableOpacity, StyleSheet, Text, View } from 'react-native'
import React, {useState} from 'react'


//API
const JOKE_API = 'https://official-joke-api.appspot.com/jokes/random';




//fetching the joke from the joke api
const getRandomJoke = async () => {
  try {
    const result = await fetch(JOKE_API, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    });


    //on success
    if(result.status === 200) {
      return result.json();
    }
    return null;


  } catch (error) {
    console.log("Error", error);
  }
}


export default function App() {
  const [punchline, setPucnline] = useState('');
  const [setup, setSetup] = useState('');


  const generateJoke = async () => {
    const randomJokeData = await getRandomJoke();


    //update the setup and puchline varible if randomJokeData is not null
    if(randomJokeData != null) {
      setSetup(randomJokeData['setup']);
      setPucnline(randomJokeData['punchline']);
    }
  }


  return (
    <View style={styles.container}>
      <Text style={styles.headline}>Setup</Text>
      <Text style={styles.textBody}>{setup}</Text>
      <Text style={styles.headline}>Puchline</Text>
      <Text style={styles.textBody}>{punchline}</Text>
      <TouchableOpacity onPress={generateJoke} style={styles.buttonStyle}>
        <Text style={styles.buttonText}>New Joke</Text>
      </TouchableOpacity>
    </View>
  )
}


//stylesheet
const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 30
  },
  headline: {
    fontSize: 25,
    padding: 6,
    color: 'black',
    letterSpacing: 1,
    fontWeight: 'bold'
  },
  textBody: {
    fontSize: 18,
    color: 'black',
    paddingHorizontal: 20,
    paddingVertical: 10
  },
  buttonStyle: {
    backgroundColor: 'green',
    paddingHorizontal: 20,
    paddingVertical: 15,
    margin: 15,
    borderRadius: 4,
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    fontWeight:'bold',
    alignSelf:'center'
  }
})

Working with APIs Calls In React Native

How to make a POST API call in React Native

To perform the POST API operation in React Native, we will use the same fetch React Native API. We need to pass in the method parameter with the value of "POST" and include the necessary body parameters. By passing in the appropriate body parameters, we can send data to the server and handle the response accordingly using the Fetch API in our React Native application. This can be seen in the following code example.

const Login_API = 'YOUR_API_URL';


const loginUser = async () => {
  try {
    const result = await fetch(Login_API, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: 'YOUR_EMAIL_ID',
        password: 'YOUR_PASSWORD'
      })
    });


    //on success
    if(result.status === 200) {
      const jsonResult = await result.json();
      return jsonResult;
    }
    return null;




  } catch (error) {
    console.log("Error", error);
  }
}

Conclusion

fetch library to make API calls. We've discussed how to make GET and POST requests. While numerous different libraries and ways of performing API requests exist, the default fetch library is a good place to start for most use cases. Happy Coding:)


Similar Articles