To make multiple serial API requests in React using Axios, where each request depends on the previous response, follow these steps:
Step-by-Step Solution:
- Create React State: Track loading state, errors, and final data.
- Use
useEffect for Requests: Trigger the sequence when the component mounts.
- Chain Requests with
async/await: Execute requests sequentially inside an async function.
- Handle Errors: Catch and display any errors during the requests.
Implementation:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const SerialRequestsComponent = () => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [finalData, setFinalData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
setError(null);
// First request: Get user data
const userResponse = await axios.get('/api/user/123');
const userId = userResponse.data.id;
// Second request: Use userId to fetch posts
const postsResponse = await axios.get(`/api/user/${userId}/posts`);
const postId = postsResponse.data[0].id;
// Third request: Use first post's ID to get comments
const commentsResponse = await axios.get(`/api/posts/${postId}/comments`);
// Store the final result
setFinalData({
user: userResponse.data,
posts: postsResponse.data,
comments: commentsResponse.data
});
} catch (err) {
setError(err.message || 'An error occurred');
} finally {
setLoading(false);
}
};
fetchData();
}, []); // Empty dependency array runs once on mount
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
{finalData && (
<>
<h1>{finalData.user.name}'s Posts</h1>
<ul>
{finalData.posts.map(post => (
<li key={post.id}>
{post.title}
<ul>
{finalData.comments
.filter(comment => comment.postId === post.id)
.map(comment => (
<li key={comment.id}>{comment.text}</li>
))}
</ul>
</li>
))}
</ul>
</>
)}
</div>
);
};
export default SerialRequestsComponent;
Key Points:
- Sequential Execution: Each
await pauses execution until the request completes.
- Error Handling: Single
try/catch block captures errors from any request.
- Cleanup:
finally block ensures loading state is reset regardless of success/failure.
- Data Flow: Responses from earlier requests are used as parameters for subsequent calls.
Alternative with Promise Chaining:
useEffect(() => {
setLoading(true);
axios.get('/api/user/123')
.then(userResponse => {
const userId = userResponse.data.id;
return axios.get(`/api/user/${userId}/posts`);
})
.then(postsResponse => {
const postId = postsResponse.data[0].id;
return axios.get(`/api/posts/${postId}/comments`);
})
.then(commentsResponse => {
setFinalData(commentsResponse.data);
})
.catch(err => setError(err.message))
.finally(() => setLoading(false));
}, []);
Best Practices:
- Cancel Requests: Use Axios'
CancelToken to abort requests if the component unmounts mid-request.
- Modularize: Break complex chains into separate functions for readability.
- Loading States: Consider granular loading states for each request if needed.
- Dependencies: Add dependencies to
useEffect if the sequence should re-run when props/state change.
This pattern ensures requests execute in order while maintaining React's component lifecycle integrity.