OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Handling Complex Nested API Requests in React.js with Efficient State Management

  • Thread starter Thread starter Yash Vara
  • Start date Start date
Y

Yash Vara

Guest
I'm working on a React.js application where I need to handle complex nested API requests efficiently and manage the state accordingly. The scenario is as follows:

I have an API endpoint that returns a list of users. For each user, I need to make additional API requests to fetch their details and their associated posts. Each post may have comments, which require another layer of API requests. Here's a simplified version of what the data structure looks like:

Code:
[
  {
    "id": 1,
    "name": "User1",
    "details": {
      "age": 25,
      "email": "[email protected]"
    },
    "posts": [
      {
        "id": 101,
        "title": "Post1",
        "comments": [
          {
            "id": 1001,
            "content": "Comment1"
          }
        ]
      }
    ]
  }
]

Requirements:

  • The list of users and store it in the state.
  • For each user, fetch their details and update the state.
  • For each user's post, fetch the comments and update the state.
  • Ensure efficient state management to avoid unnecessary re-renders and potential performance issues.
  • Handle loading states and error handling for each level of the nested requests.

This is my initial approach using useEffect and useState, but it quickly becomes cumbersome and inefficient:

Code:
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const App = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const userResponse = await axios.get('/api/users');
        const usersData = userResponse.data;

        for (let user of usersData) {
          const userDetails = await axios.get(`/api/users/${user.id}/details`);
          user.details = userDetails.data;

          const userPosts = await axios.get(`/api/users/${user.id}/posts`);
          user.posts = userPosts.data;

          for (let post of user.posts) {
            const postComments = await axios.get(`/api/posts/${post.id}/comments`);
            post.comments = postComments.data;
          }
        }

        setUsers(usersData);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {users.map(user => (
        <div key={user.id}>
          <h2>{user.name}</h2>
          <p>Age: {user.details.age}</p>
          <p>Email: {user.details.email}</p>
          {user.posts.map(post => (
            <div key={post.id}>
              <h3>{post.title}</h3>
              {post.comments.map(comment => (
                <p key={comment.id}>{comment.content}</p>
              ))}
            </div>
          ))}
        </div>
      ))}
    </div>
  );
};

export default App;

Issues I'm facing:

  • The nested loops for fetching data are making the application slow.
  • Managing state updates for deeply nested structures is becoming unmanageable.
  • The component re-renders multiple times, leading to performance degradation.

<p>I'm working on a React.js application where I need to handle complex nested API requests efficiently and manage the state accordingly. The scenario is as follows:</p>
<p>I have an API endpoint that returns a list of users.
For each user, I need to make additional API requests to fetch their details and their associated posts.
Each post may have comments, which require another layer of API requests.
Here's a simplified version of what the data structure looks like:</p>
<pre><code>[
{
"id": 1,
"name": "User1",
"details": {
"age": 25,
"email": "[email protected]"
},
"posts": [
{
"id": 101,
"title": "Post1",
"comments": [
{
"id": 1001,
"content": "Comment1"
}
]
}
]
}
]
</code></pre>
<p>Requirements:</p>
<ul>
<li>The list of users and store it in the state.</li>
<li>For each user, fetch their details and update the state.</li>
<li>For each user's post, fetch the comments and update the state.</li>
<li>Ensure efficient state management to avoid unnecessary re-renders and potential performance issues.</li>
<li>Handle loading states and error handling for each level of the nested requests.</li>
</ul>
<p>This is my initial approach using useEffect and useState, but it quickly becomes cumbersome and inefficient:</p>
<pre><code>import React, { useEffect, useState } from 'react';
import axios from 'axios';

const App = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
const fetchUsers = async () => {
try {
const userResponse = await axios.get('/api/users');
const usersData = userResponse.data;

for (let user of usersData) {
const userDetails = await axios.get(`/api/users/${user.id}/details`);
user.details = userDetails.data;

const userPosts = await axios.get(`/api/users/${user.id}/posts`);
user.posts = userPosts.data;

for (let post of user.posts) {
const postComments = await axios.get(`/api/posts/${post.id}/comments`);
post.comments = postComments.data;
}
}

setUsers(usersData);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};

fetchUsers();
}, []);

if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;

return (
<div>
{users.map(user => (
<div key={user.id}>
<h2>{user.name}</h2>
<p>Age: {user.details.age}</p>
<p>Email: {user.details.email}</p>
{user.posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
{post.comments.map(comment => (
<p key={comment.id}>{comment.content}</p>
))}
</div>
))}
</div>
))}
</div>
);
};

export default App;
</code></pre>
<p>Issues I'm facing:</p>
<ul>
<li>The nested loops for fetching data are making the application slow.</li>
<li>Managing state updates for deeply nested structures is becoming unmanageable.</li>
<li>The component re-renders multiple times, leading to performance degradation.</li>
</ul>
 

Latest posts

A
Replies
0
Views
1
Ashrik Ahamed
A
A
Replies
0
Views
1
Ashrik Ahamed
A

Online statistics

Members online
1
Guests online
3
Total visitors
4
Top