Welcome to our comprehensive guide on the fetch API in React JS! In this tutorial, we'll learn how to interact with APIs asynchronously, making your applications more dynamic and powerful. Let's get started!
The fetch API is a built-in browser function that allows you to make HTTP requests and receive responses as a Promise in JavaScript. It's a modern alternative to XMLHttpRequest (XHR) and is widely used in React JS for fetching data from APIs.
fetch API is more straightforward and has a cleaner syntax.fetch API returns a Promise, making it easier to handle asynchronous operations and chain multiple API calls.fetch API.To get started, make sure you have the following prerequisites:
npm install -g create-react-appcreate-react-app my-appNow, let's dive into our first example and see how to fetch data using the fetch API.
import React, { useEffect, useState } from 'react';
function App() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error:', error));
}, []);
return (
<div>
<h1>Fetched Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export default App;In this example, we use the useEffect hook to fetch data from an API when the component mounts. We then set the fetched data in the component's state using the setData function.
š Note:
useEffect is a React hook that lets you perform side effects in function components.JSON.stringify function to format our data as a string for display purposes.What is the purpose of the `useEffect` hook in the provided example?
When working with APIs, errors may occur. Here's how to handle errors using the fetch API:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => setData(data))
.catch(error => console.error('Error:', error));In this example, we check if the response is ok before returning the data. If the response is not ok, we throw an error and handle it in the catch block.
Async/await makes handling promises easier and more readable. Here's an example of making API requests using async/await:
async function fetchData() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
setData(data);
}
useEffect(() => {
fetchData();
}, []);In this example, we use the async and await keywords to make the code more readable and easier to understand.
Which keyword is used to make asynchronous functions more readable in JavaScript?
Sometimes, you may need to make multiple API calls in your application. Here's an example of making multiple API calls using fetch API:
async function fetchData() {
const response1 = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data1 = await response1.json();
const response2 = await fetch('https://jsonplaceholder.typicode.com/todos/2');
const data2 = await response2.json();
setData([data1, data2]);
}
useEffect(() => {
fetchData();
}, []);In this example, we make two API calls and set the fetched data in the component's state as an array.
Congratulations! You've now learned the basics of using the fetch API in React JS. You've seen how to fetch data from APIs, handle errors, and even make multiple API calls using async/await.
Remember to practice and experiment with the concepts you've learned to solidify your understanding. Happy coding! š”šÆš