0

I have a React app for fetching and displaying hundreds of posts. The API I'm working with supports fetching multiple posts in a single request (https://my.api/posts/1,2,3 would return posts with ids 1, 2 and 3), and I want to make use of this feature.

How do I make it so, that once all components have finished rendering and called their usePost(id) selector hooks, the app batches all of the requested post ids into a single API request? I know I can use thunks (useProfile, useUser, usePost hooks in the example below use thunks), but how can I store requested ids until after everything is rendered, and then make a request with these ids?

export default function Page() {
  const myProfile = useProfile();

  return (
    <div>
      {myProfile?.followed.map(authorId => (<PostList authorId={authorId}/>))}
    </div>
  );
}
export function PostList({ authorId }) {
  const user = useUser(authorId);

  return (
    <div>
      {user?.posts.map(postId => (<Post id={postId}/>))}
    </div>
  );
}
export function Post({ id }) {
  const post = usePost(id);

  return <div>{post?.content}</div>;
}

And instead making a request for every single post:

GET /my_profile   // {followed:[1,2,3]}
GET /users/1      // {posts:[100,102]}
GET /users/2      // {posts:[201,205,207]}
GET /users/3      // {posts:[305,319,378]}
GET /posts/100    // {content:"Post 100"}
GET /posts/102    // {content:"Post 102"}
GET /posts/201    // {content:"Post 201"}

... // hunderds of other posts

The app would batch these requests like this:

GET /my_profile              // {followed:[1,2,3]}
GET /users/1,2,3/posts       // [{posts:[100,102]}, {posts:[201,205,207]}, ...]
GET /posts/100,102,201,...   // [{content:"Post 100"}, {content:"Post 102"}, ...]

0 Answers0