Fetching Data in React Native.
Course Title: Building Mobile Applications with React Native Section Title: Working with APIs and Data Fetching Topic: Fetching data using fetch API and Axios
Overview of Fetching Data
In the previous topic, we discussed the basics of REST APIs and GraphQL. In this topic, we will focus on how to fetch data from APIs using the fetch API and Axios in our React Native application.
What is the Fetch API?
The Fetch API is a modern, promise-based API for requesting resources across the network. It is built into the browser and can be used in React Native applications. The fetch API provides an easy-to-use API for fetching resources asynchronously.
What is Axios?
Axios is a promise-based HTTP client for the browser and Node.js. It provides an easy-to-use API for making HTTP requests in JavaScript.
Choosing between Fetch API and Axios
Both the Fetch API and Axios can be used to fetch data in React Native applications. The choice between the two depends on personal preference and project requirements.
- The Fetch API is a built-in API and does not require an additional library.
- Axios provides more features such as automatic JSON data parsing and canceling requests.
Fetching Data using the Fetch API
To fetch data using the fetch API, we need to call the fetch function and pass the URL of the resource we want to fetch.
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
const FetchExample = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const json = await response.json();
setData(json);
} catch (error) {
setError(error.message);
}
};
fetchData();
}, []);
return (
<View>
{data ? (
<Text>Data fetched successfully!</Text>
) : (
<Text>Error fetching data: {error}</Text>
)}
</View>
);
};
export default FetchExample;
In this example, we are fetching data from the JSONPlaceholder API.
Handling Errors
We can handle errors using try-catch blocks. If an error occurs while fetching data, we can display an error message to the user.
Canceling Requests
We can cancel fetch requests by registering an AbortController and using the AbortSignal to cancel the request.
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
const FetchExample = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
const fetchData = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
signal,
});
const json = await response.json();
setData(json);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Request was aborted');
} else {
setError(error.message);
}
}
};
fetchData();
return () => {
abortController.abort();
};
}, []);
return (
<View>
{data ? (
<Text>Data fetched successfully!</Text>
) : (
<Text>Error fetching data: {error}</Text>
)}
</View>
);
};
export default FetchExample;
In this example, we are registering an AbortController and using the AbortSignal to cancel the request when the component unmounts.
Fetching Data using Axios
To fetch data using Axios, we need to install Axios in our project.
npm install axios
Then, we can use Axios to fetch data.
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';
const AxiosExample = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
setData(response.data);
} catch (error) {
setError(error.message);
}
};
fetchData();
}, []);
return (
<View>
{data ? (
<Text>Data fetched successfully!</Text>
) : (
<Text>Error fetching data: {error}</Text>
)}
</View>
);
};
export default AxiosExample;
In this example, we are fetching data from the JSONPlaceholder API using Axios.
Handling Errors
We can handle errors using try-catch blocks. If an error occurs while fetching data, we can display an error message to the user.
Canceling Requests
We can cancel Axios requests by creating a CancelToken and using it with the request.
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import axios, { CancelToken } from 'axios';
const AxiosExample = () => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const cancelToken = CancelToken.source();
const fetchData = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts', {
cancelToken: cancelToken.token,
});
setData(response.data);
} catch (error) {
if (axios.isCancel(error)) {
console.log('Request was cancelled');
} else {
setError(error.message);
}
}
};
fetchData();
return () => {
cancelToken.cancel();
};
}, []);
return (
<View>
{data ? (
<Text>Data fetched successfully!</Text>
) : (
<Text>Error fetching data: {error}</Text>
)}
</View>
);
};
export default AxiosExample;
In this example, we are creating a CancelToken and using it with the request. We also cancel the request when the component unmounts.
What's Next?
In the next topic, we will discuss handling asynchronous operations with Promises and async/await.
Do you have any questions or need help with this topic? Leave a comment below.
For more information on the fetch API, you can refer to the MDN Web Docs.
For more information on Axios, you can refer to the Axios Documentation.
For more information on AbortController, you can refer to the MDN Web Docs.
For more information on CancelToken, you can refer to the Axios Documentation.
Images

Comments