Fetch posts with comments for a user

by jacobwsmith

JavaScript

// async function getPostsWithComments(userId) {
//   const posts = await fetch(
//     `https://jsonplaceholder.typicode.com/posts?userId=${userId}`,
//   )
//     .then((res) => res.json())
//     .catch((err) => console.log("Error fetching posts", err));
//   const comments = await fetch(
//     `https://jsonplaceholder.typicode.com/comments`,
//   ).then((res) => res.json());
//   let userPosts = [];
//   for (let i = 0; i < posts.length; i++) {
//     const post = posts[i];
//     const postComments = [];
//     for (let j = 0; j < comments.length; j++) {
//       if (comments[j].postId == post.id) {
//         postComments.push(comments[j]);
//       }
//     }
//     post.comments = postComments;
//     userPosts.push(post);
//   }
//   return userPosts;
// }

async function getPostsWithComments(userId) {
  const [postRes, commentRes] = await Promise.all([
    fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`),
    fetch(`https://jsonplaceholder.typicode.com/comments`)
  ])
  if(!postRes.ok || !commentRes.ok) throw new Error('did not get data over the network')
  const [posts, comments] = await Promise.all([postRes.json(), commentRes.json()])
  const commentsByPost = comments.reduce((acc, c) => {
    if(!acc[c.postId]) {
      acc[c.postId] = []
    }
    acc[c.postId].push(c)
    return acc;
  }, {});
  
  return posts.map(post => {
    return {
      ...post,
      comments: commentsByPost[post.id] || []
    }
  })
}

getPostsWithComments(1).then((result) => {
  console.log(result)
})