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.



.display{
  display: flex;
  justify-content: center;
  width: 100%;
}
.display .posts{
  margin-top: 1rem;
  display: flex;
  flex-direction: column;
  gap: 5rem;
  width: 50%;
 
}
.display .posts div{
  padding: 1rem;
  border: 2px solid black;
  border-radius: 0.75rem;
}
.display .posts div:hover{
  transform: scale(1.05);
}


3. Now, navigate to the App.jsx file and replace the existing code with the following code: 


import './App.css';
import { useEffect,useState } from 'react';
function App() {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    async function fetchData (){
      let url = `https://jsonplaceholder.typicode.com/posts`;
      try {
        let response = await fetch(url);
        let data = await response.json();
        setPosts(data);
        console.log(data);
      }
      catch (err) {
        console.log(err)
      }
    }
    fetchData();
  }, [])

  return (
    <div className='display'>
      <div className="posts">
      {posts.map(post => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.body}</p>
        </div>
      ))}
      </div>
    </div>
  );
}

export default App;


Explanation:-

  1. Import Statements:

    • import './App.css';: This imports the CSS file App.css for styling.
    • import { useEffect, useState } from 'react';: This imports the useEffect and useState hooks from the React library. These hooks are used for managing side effects and state in functional components, respectively.

  2. Functional Component App:

    • function App() { ... }: This defines the App component as a functional component.
    • const [posts, setPosts] = useState([]);: This line initializes a state variable posts using the useState hook. Initially, posts is an empty array, and setPosts is a function used to update the posts state.
  3. useEffect Hook:

    • useEffect(() => { ... }, []);: This useEffect hook runs when the component mounts (due to the empty dependency array []). Inside the hook, an asynchronous function fetchData is defined and immediately invoked.

  4. Fetching Data:

    • async function fetchData() { ... }: This asynchronous function fetchData is defined within the useEffect 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 the posts state with the fetched data.
    • console.log(data);: This logs the fetched data to the console for debugging purposes.

  5. Rendering Posts:

    • return ( ... );: This is the JSX returned by the App component.
    • <div className='display'> ... </div>: This wraps the content of the component with a div with the class name display.
    • <div className="posts"> ... </div>: This div holds the rendered posts.
    • {posts.map(post => (...))}: This maps over the posts array and renders each post as a div with its title and body. The key 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

Popular posts from this blog

Routing in React

Building a weather app using React.js