To avoid callback hell, JavaScript promises provide a more elegant solution for handling nested fetch calls in React by allowing us to chain then
methods and make the code easier to read and maintain.
Here’s an example of how we can use promises in a React component to handle nested fetch calls:
import React, { useState, useEffect } from 'react';
const PostComponent = () => {
const [posts, setPosts] = useState([]);
const [comments, setComments] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(posts => {
setPosts(posts);
let postPromises = posts.map(post => {
return fetch(`https://jsonplaceholder.typicode.com/posts/${post.id}/comments`)
.then(response => response.json());
});
return Promise.all(postPromises);
})
.then(commentsArray => {
setComments(commentsArray);
setLoading(false);
})
.catch(error => {
console.error(error);
setLoading(false);
});
}, []);
return (
<div>
{loading ? (
<p>Loading...</p>
) : (
<>
<h2>Posts</h2>
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
<h2>Comments</h2>
<ul>
{comments.map((commentsArray, index) => (
<li key={index}>
<ul>
{commentsArray.map(comment => (
<li key={comment.id}>{comment.body}</li>
))}
</ul>
</li>
))}
</ul>
</>
)}
</div>
);
};
export default PostComponent;
In this example, we first use the useEffect
hook to fetch a list of posts from the API. Then, we use the map
method to create an array of promises for fetching the comments of each post. The Promise.all
method is used to wait for all promises to resolve, and the resolved values are stored in the comments
state.
The component then displays the posts and comments on the page, showing a “Loading…” message while the data is being fetched.
By using promises, we can handle nested fetch calls in a clean and organized manner, and ensure that the next fetch call is only performed after the previous one is completed. This makes the code easier to read and maintain, and ensures that the component only updates with accurate data.
Git repo for nested HTTP calls in react using promise – https://github.com/refarchdev/nestedhttpcallsinreact
Demo: