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.cssfor styling.import { useEffect, useState } from 'react';: This imports theuseEffectanduseStatehooks 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 theAppcomponent as a functional component.const [posts, setPosts] = useState([]);: This line initializes a state variablepostsusing theuseStatehook. Initially,postsis an empty array, andsetPostsis a function used to update thepostsstate.
useEffectHook:useEffect(() => { ... }, []);: ThisuseEffecthook runs when the component mounts (due to the empty dependency array[]). Inside the hook, an asynchronous functionfetchDatais defined and immediately invoked.
Fetching Data:
async function fetchData() { ... }: This asynchronous functionfetchDatais defined within theuseEffecthook. 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 thepostsstate 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 theAppcomponent.<div className='display'> ... </div>: This wraps the content of the component with adivwith the class namedisplay.<div className="posts"> ... </div>: Thisdivholds the rendered posts.{posts.map(post => (...))}: This maps over thepostsarray and renders each post as adivwith itstitleandbody. Thekeyprop 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