Fetching API Data with React.JS using Fetch
In React, we can use both fetch and AJAX to make API calls. However, we usually prefer to use fetch because it is a built-in API in modern browsers and does not require any external libraries.
In this article, we will go over the steps for fetching API data with React.js. Let's get started-
- Create a Child Component
- Import the Necessary Modules to Parent
- Define the useStae and useEffect hook
- Render the Child Component
First we need to create a child component MyComponent.js that will receive a props of data to render:
import React from 'react';
function MyComponent({data}) {
return (
<div>
{data.map(item => (
<div key={item.id}>
<h2>{item.title}</h2>
<p>{item.body}</p>
</div>
))}
</div>
);
}
export default MyComponent;
Now, we will import the necessary modules to our App.js component for making API calls.
import React, { useState, useEffect } from 'react';
function App() {
return (
<div>
<h1>Fetch Data with React</h1>
</div>
);
}
export default App;
We need to define the state where we will store the API response. We can use the useState hook to define the state. We also need to use the useEffect hook to make the API call and update the state. We will use fetch for making HTTP requests. Here's an example:
import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
<h1>Fetch Data with React</h1>
</div>
);
}
export default App;
Here, we fetch data from api and update our data state.
Next, we need to render the component in our App.js component and pass the data as props
to our MyComponent.js component. We can import and use the child component in our App.js file like this:
import React, { useState, useEffect } from 'react';
import MyComponent from './MyComponent';
function App() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
<h1>Fetch Data with React</h1>
<MyComponent data={data} />
</div>
);
}
export default App;
This will render the MyComponent in our application and display the fetched data.
That's all for today. Thanks for reading the article.