Data Fetching using useEffect
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
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.Solution Walkthrough for Data Fetching using useEffect
Spoiler Alert!
Don't read this unless you've already solved the problem.
useEffect
that determines when the effect should run.Async/Await: The async/await syntax makes it easier to work with promises and fetch data from APIs.
Fetch API: The Fetch API provides a simple interface for fetching resources, making it easier to perform HTTP requests.
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([]);
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]);
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>
);
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.