logo
logo

Data Fetching using useEffect

Easy

Data Fetching using useEffect

Easy
Create a
UserPosts
component that fetches and displays a list of posts for a given user ID using the JSONPlaceholder API (https://jsonplaceholder.typicode.com/). The component should fetch data when it mounts and update the data when the user ID prop changes. This exercise will help you understand how to use the
useEffect
hook for data fetching and the importance of the dependency array.

Expectations

  • Fetch data from the JSONPlaceholder API.

  • Display a list of posts for the given user ID.

  • Refetch data when the user ID prop changes.

Background

Understanding how to fetch data with
useEffect
is crucial as it is a common requirement in real-world applications. This exercise will help you learn how to fetch data on component mount and when the user ID prop changes, which is an essential pattern in React applications.
Console
Submit
Solution
00:00

Solution Walkthrough for Data Fetching using useEffect

Key Concepts

  1. Dependency Array: The dependency array is an optional second argument passed to
    useEffect
    that determines when the effect should run.
  2. Async/Await: The async/await syntax makes it easier to work with promises and fetch data from APIs.

  3. Fetch API: The Fetch API provides a simple interface for fetching resources, making it easier to perform HTTP requests.

Solution Walkthrough:

Initialize state variable
posts
with an empty array: We create a state variable
posts
using the
useState
hook and set its initial value to an empty array.
const [posts, setPosts] = useState([]);
Create an async function to fetch data and update the
posts
state: We use the
useEffect
hook to fetch data when the component mounts and when the
userId
prop changes. We create an async function
fetchData
inside the
useEffect
hook to fetch data from the JSONPlaceholder API using the Fetch API and the async/await syntax.
useEffect(() => {
  const fetchData = async () => {
    const response = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`);
    const data = await response.json();
    setPosts(data);
  };
  fetchData();
}, [userId]);
Render the list of posts: We use the
map
function to render the list of posts in the component.
return (
  <div>
    {posts.map((post) => (
      <div key={post.id}>
        <h3>{post.title}</h3>
        <p>{post.body}</p>
      </div>
    ))}
  </div>
);
This solution demonstrates the key concepts of using the
useEffect
hook for data fetching, controlling when the effect runs using the dependency array, and working with the Fetch API and async/await syntax to fetch data from an API.