How to fetch data from an API in React.js?
In my previous post, we discussed about all the hooks that are used in React along with some examples. Now, in this post I will show you how to fetch data from an API in React.js via a small project. For our today's project, we will be using the JSONPlaceholder API. In this project we will fetch all the posts from the API endpoint:https://jsonplaceholder.typicode.com/posts and show them on our React app.
Step by Step guide to create the project:-
1. Create a React app in your desired directory. If you don't know how to create a React app, go to my post on React.js tutorial on how to create a React app Step by Step guide.
2. Navigate to the App.css file and delete all custom CSS code from App.css and copy this code This code provides minimal styling for our app component. You can of course, add more custom CSS or include frameworks like Bootstrap or Tailwind CSS in order to make your project more beautiful.
3. Now, navigate to the App.jsx file and replace the existing code with the following code:
Explanation:-
Import Statements:
import './App.css';
: This imports the CSS fileApp.css
for styling.import { useEffect, useState } from 'react';
: This imports theuseEffect
anduseState
hooks from the React library. These hooks are used for managing side effects and state in functional components, respectively.
Functional Component
App
:function App() { ... }
: This defines theApp
component as a functional component.const [posts, setPosts] = useState([]);
: This line initializes a state variableposts
using theuseState
hook. Initially,posts
is an empty array, andsetPosts
is a function used to update theposts
state.
useEffect
Hook:useEffect(() => { ... }, []);
: ThisuseEffect
hook runs when the component mounts (due to the empty dependency array[]
). Inside the hook, an asynchronous functionfetchData
is defined and immediately invoked.
Fetching Data:
async function fetchData() { ... }
: This asynchronous functionfetchData
is defined within theuseEffect
hook. It's responsible for fetching data from the JSONPlaceholder API.let url = 'https://jsonplaceholder.typicode.com/posts';
: This defines the URL from which the data will be fetched.let response = await fetch(url);
: This line sends a GET request to the specified URL and awaits the response.let data = await response.json();
: This parses the JSON response into JavaScript objects.setPosts(data);
: This updates theposts
state with the fetched data.console.log(data);
: This logs the fetched data to the console for debugging purposes.
Rendering Posts:
return ( ... );
: This is the JSX returned by theApp
component.<div className='display'> ... </div>
: This wraps the content of the component with adiv
with the class namedisplay
.<div className="posts"> ... </div>
: Thisdiv
holds the rendered posts.{posts.map(post => (...))}
: This maps over theposts
array and renders each post as adiv
with itstitle
andbody
. Thekey
prop is used to uniquely identify each post element.
4. Now, run npm start in your terminal.
5. Your website must look something like this:
You now know how to fetch data from an API in React.
Comments
Post a Comment