I've been trying to integrate my posts into my user table for 2 days with the Json PlaceHolder API with nextJS. I can't seem to find the right logic and after many tries and searches I could use a little help.
I tried the filter() method but this one doesn't seem very conventional to me. I'm convinced that there is a very simple way with conditions but I can't integrate it into my map()
export default function Home() {
//State
const [users, setUsers] = useState([]);
const [posts, setPosts] = useState([]);
//Get Users
useEffect(() => {
const url = `https://jsonplaceholder.typicode.com`;
axios
.get(`${url}/users`)
.then((response) => setUsers(response.data));
axios
.get(`${url}/posts`)
.then((response) => setPosts(response.data));
}, []);
const listPost = posts.filter((post) => {
const listUser = users.filter((user) => {
if (post.userId === user.id) console.log('matching post');
else {
console.log('undefined post');
}
});
});
return (
<div>
<main className='container'>
<table className='rwd-table'>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>username</th>
<th>post-userId</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.username}</td>
<td></td>
</tr>
))}
</tbody>
</table>
</main>
<footer>
</footer>
</div>
);
}
CodePudding user response:
So it seems like you want to associate
users with posts, few things.
- You might don't need to set both users and posts on the state (thats 2 setStates) but you can just merge them together so yo end up with a data structure like
{ id: number, name: string, ..., posts: Array<Post> } // this is a user
, which is what you are looking for.
BONUS:
- Since Posts and users API calls don't depend on each other you can make those 2 calls at the same time, see
const [users, posts] = await Promise.all([
fetchAxiosData("users"),
fetchAxiosData("posts")
]);
made
fetchAxiosData
so you don't worry about the HTTP layer at the component levelAdd
error
andisFetching
state, its always good to have an idea if there is an error or you are loading (NOTE: some libraries like swr or react-query already handled this for you, you might wanna take a look)
I will leave the UI implementation to you, not sure how do you want to show the posts on the table, maybe just the title?
you can do <td>{user.posts.map(({ title }) => title).join(", ")}</td>
Here is the Codesandbox for you to play around