Hello Readers, CoolMonkTechie heartily welcomes you in this article (The most popular best ways to make REST API Calls in React Native ).
In this article, we will learn about different best ways to make REST API Calls in React Native. Many mobile apps need to load resources from a remote URL. We may want to make a POST request to a REST API, or we may need to fetch a chunk of static content from another server.
Applications on the web and mobile devices often cannot store all the information that they need. Therefore, they have to reach out to the web to update data, retrieve data, or request a service from a third-party. The transaction that takes place between two devices (client and server) is called an API call. An API (application programming interface) typically will use the REST design paradigm to manage all how it can be accessed (called).
This article shows the fetch
function and the axios
library. Both methods achieve the same task, making an HTTP call, but they go about it in slightly different ways.
A famous quote about learning is :
” The expert in anything was once a beginner. “
So Let’s begin.
Using Fetch
React Native provides the Fetch API for our networking needs. Fetch will seem familiar if we have used XMLHttpRequest
or other networking APIs before. The Fetch API
is a built-in Javascript function. We can use fetch
by providing the URL for the location of our content. This will send a GET request to that URL.
Making Requests
In order to fetch content from an arbitrary URL, we can pass the URL to fetch:
fetch('https://mywebsite.com/mydata.json');
Fetch also takes an optional second argument that allows us to customize the HTTP request. We may want to specify additional headers, or make a POST request:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue'
})
});
We can follow at the Fetch Request docs for a full list of properties.
Handling The Response
The above examples show how we can make a request. Most times, we will want to do something with the response.
Networking is an inherently asynchronous operation. Fetch methods will return a Promise that makes it straightforward to write code that works asynchronously:
const getMoviesFromApi = () => {
return fetch('https://reactnative.dev/movies.json')
.then((response) => response.json())
.then((json) => {
return json.movies;
})
.catch((error) => {
console.error(error);
});
};
We can read through the above code like;
- Fetch the data at the URL
'https://reactnative.dev/movies.json'
- Then, transform the response into JSON
- Then, return the
movies
property on the JSON object - If there is an error, log the error to the console.
We can also use the async
/ await
syntax in a React Native app:
const getMoviesFromApiAsync = async () => {
try {
let response = await fetch(
'https://reactnative.dev/movies.json'
);
let json = await response.json();
return json.movies;
} catch (error) {
console.error(error);
}
};
We need to catch any errors that may be thrown by fetch
, otherwise they will be dropped silently.
Fetch Example
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
export default App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://reactnative.dev/movies.json')
.then((response) => response.json())
.then((json) => setData(json.movies))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Text>{item.title}, {item.releaseYear}</Text>
)}
/>
)}
</View>
);
};
By default, iOS will block any request that’s not encrypted using SSL. If we need to fetch from a cleartext URL (one that begins with http
), then App Transport Security exception will first need to add.
It is more secure to add exceptions only for those domains, If we know ahead of time to need to access the domains; if we do not know the domains until runtime, ATS can completely disable.
This is a simple way to send HTTP requests as soon as possible. However, another popular method for sending HTTP requests is with third-party libraries.
Using XMLHttpRequest API
The XMLHttpRequest API is built into React Native. This means that we can use third-party libraries such as frisbee or axios that depend on it, or we can use the XMLHttpRequest API directly if we prefer.
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
} else {
console.warn('error');
}
};
request.open('GET', 'https://mywebsite.com/endpoint/');
request.send();
The security model for XMLHttpRequest differs from on web, as there is no concept of CORS in native apps.
Using WebSocket Protocal
React Native also supports WebSockets , a protocol which provides full-duplex communication channels over a single TCP connection.
var ws = new WebSocket('ws://host.com/path');
ws.onopen = () => {
// connection opened
ws.send('something'); // send a message
};
ws.onmessage = (e) => {
// a message was received
console.log(e.data);
};
ws.onerror = (e) => {
// an error occurred
console.log(e.message);
};
ws.onclose = (e) => {
// connection closed
console.log(e.code, e.reason);
};
Using Axios Library
The Axios is a Javascript library used to make HTTP requests, and it supports the Promise API that is native to JS ES6. The Axios library has grown in popularity alongside the increase in apps that exchange information using JSON. Three things that make the Axios library so useful are the ability to;
- Intercept requests and responses
- Transform request and response data
- Automatically transform data for JSON
Axios Library Example
import Axios from 'axios'
Axios({
url: '/data',
method: 'get',
baseURL: 'https://example.com',
transformRequest: [function (data, headers) {
// Do whatever you want to transform the data
return data;
}],
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {
name: 'Some Name'
},
})
In the above example, we have passed a configuration object that calls an example URL with a GET request. We’ll notice that some parameter names are common between fetch
and Axios
.
Next, let’s look at a smaller GET request.
axios.get('https://example.com/data')
.then(function (response) {
return response.names;
})
.catch(function (error) {
console.log(error);
})
We are calling the same URL as we did with the fetch
API, but we don’t have to manually transform the response object into JSON. Axios has more features that can be useful with bigger applications.
That’s all about in this article.
Conclusion
In this article, we understood about different best ways to make REST API Calls in React Native. This article showed the fetch and axios library usage with code snippets in React Native .
Thanks for reading! I hope you enjoyed and learned about REST API Calls concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
You can also follow official website and tutorials of React Native as below links :
If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.
Thanks again Reading. HAPPY READING!!???