How to make API calls in react native apps
In this tutorial, we will implement all the provided methods for API calls into React Native application.
In this project, we will learn different methods for API calls including fetch()
method and Axios
method provided by react-native. We will also see the different configurations and properties of these methods using fetch and axios
in react native applications.
Complete source code of this tutorial is available here — RNAPI__Methods
What is React-Native?
TLDR; — React Native (RN) creates cross-platform apps, more “native” than web-view apps made by Cordova / Ionic. But React Native is yet to release a stable (1.0.0_) version of the framework.
React Native is a JavaScript framework for writing natively rendering mobile applications. It’ is based on React, Facebook’s JavaScript library for building user interfaces, but instead of targeting the browser, it targets mobile platforms. Because most of the code you write can be shared between platforms, React Native makes it easy to simultaneously develop for both Android and iOS.
React Native applications render using real mobile UI components, not web-views, and will look and feel like any other native mobile application. React Native also exposes JavaScript interfaces for platform APIs, so your React Native apps can access platform features like the phone camera, or the user’s location. Facebook, Palantir, TaskRabbit etc are already using it in production for user-facing applications.
React Native and API Calls
Many mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may need to fetch a chunk of static content from another server.
React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest
or other networking APIs before.
Making requests
In order to fetch content from an arbitrary URL, you can pass the URL to fetch:
fetch('Your URL to fetch data from');
Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request:
fetch('Your URL to fetch data from', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner:
function getMoviesFromApiAsync() {
return fetch('Your URL to fetch data from')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
You can also use the proposed ES2017 async
/await
syntax in a React Native app:
async function getMoviesFromApi() {
try {
let response = await fetch(
'Your URL to fetch data from',
);
let responseJson = await response.json();
console.log(responseJSon);
return responseJson;
} catch (error) {
console.error(error);
}
}
Don’t forget to catch any errors that may be thrown by fetch
, otherwise, they will be dropped silently.
Another method to API Call is axios. Axios is a hugely popular (over 52k stars on Github) HTTP client that allows us to make GET and POST requests from the browser.
Therefore, we can use Axios with React Native to make requests to an API, return data from the API, and then do things with that data in our React app.
Why Do We Need Axios?
Most web and mobile apps store data in the cloud communicate with a service. For example, a service that gets the current weather in your local area, or returns a list of GIFs based on a search term.
Databases and web services have something called an API (Application Programming Interface) which apps can use to communicate with through a URL. In other words, an API allows apps to retrieve or send data to and from databases or web services.
Apps use HTTP requests, for example, GET, POST and PUT, to communicate with APIs. In short, Axios makes it easy for our apps to perform these commands.
Post structure
We will go in a step-by-step manner to explore all the methods for API calls. This is my break-down of the blog
STEPS
- Create a simple React Native app
- Install package
axios
. - Use different API call methods to get responses.
We have three major objectives
- React-App set up for different API calls.
- Make an interactive UI and implement the API methods.
- Getting responses and showing the result in the view.
Let’s dive right in!
Step 1 — Create a basic React Native app
First, make sure you have all pre-requisites to create a react-native app as per the official documentation.
At the time of this post, I have React-Native version 0.61.2
Create a blank react-native app (Replace APICALLS
with your own app name)
$ react-native init APICALLS
This will create a basic React-native app that you can run in a device or simulator. Let’s run the app in android using
$ react-native run-android
You’ll see the default start screen on the device/simulator.
Steps to implement
step 1 — Install axios package using the below command
yarn add axios
# or with npm
# npm i axios --save
Open up App.js and import the Axios library at the top of the file.
App.js
import axios from 'axios';
Now we have all the required concepts in detail and in easy to understand language.
Now I am going to implement each, one by one in an explained way.
Right now my App.js structure is as below image.
I have divided my logic view and styles into three different components and implemented the concept of functional and class component in this app as ApiContainer.js is a class component to handle the logic for the child component Apiview.js, which is a functional component imported in the parent component.
Let's get started and start implementing these methods in our cool react-native application but before that let us make some buttons for UI purpose so that we can click those to get responses and show the result.
View Results: —
Code View for Fetch Method: —
Code View for Axios Method: —
Code View for API UI: —
Code View API Logics: —
In the above gist you can see I have used the set timeout method for data to be loaded and till then showing loader.
Now you are all set to achieve all these methods and make UI and use according to your needs.
Complete source code of this tutorial is available here — RNAPI__Methods.
Conclusion
In this post, we learned how to implement restful API’s using fetch() and axios methods in our cool React native app. We also learned how to handle responses from these methods and use their data in the app.
With this tutorial we learned using the set timeout() method and FlatList With this tutorial, we also achieved all the navigation methods in the same application.
Complete source code of this tutorial is available here — RNAPI__Methods.