Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question