M
M
MaksN92022-04-21 13:23:54
JavaScript
MaksN9, 2022-04-21 13:23:54

How to merge two JSONPlaceholder by id?

You need to display information from https://jsonplaceholder.typicode.com/posts (title, body) and from https://jsonplaceholder.typicode.com/users (name). As I understand it, you need to combine them by id. Tell me how you can do it.

Here is my code but I am the only one here who can output the title and body.

import React, { useEffect, useState } from 'react'
import axios from 'axios' 

function Feed() {
    const [posts, setPosts] = useState([]);

    useEffect(() => {
        const fetchData = async () => {
            const result = await axios.get (
                "https://jsonplaceholder.typicode.com/posts",
            );

            setPosts(result.data);
        };
        
        fetchData();
    }, []);
        return (
               <div className='container'>
                    <div className='user-cards'>
                        {posts && 
                            posts.map(post => (
                                <div className='user-card'>
                                    <p>{post.title}</p>
                                    <p>{post.body}</p>
                                </div>
                            ))}
                    </div>
                </div>
   )
}

export {Feed}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2022-04-21
@MaksN9

const getData = type => fetch(`https://jsonplaceholder.typicode.com/${type}`).then(r => r.json());

const [ data, setData ] = useState([]);

useEffect(() => {
  Promise
    .all([ 'posts', 'users' ].map(getData))
    .then(([ posts, users ]) => {
      const usersObj = Object.fromEntries(users.map(n => [ n.id, n ]));
      setData(posts.map(n => ({
        post: n,
        user: usersObj[n.userId],
      })));
    });
}, []);

return (
  <div>
    {data.map(({ post, user }) => (
      <div>
        <h2>{post.title}</h2>
        <h3>{user.name}</h3>
        <p>{post.body}</p>
      </div>
    ))}
  </div>
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question