reactjsapiaxiosnext.jsjsonplaceholder

Json placeHolder API - Fetch Data white condition


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>
  );
}

Solution

  • So it seems like you want to associate users with posts, few things.

    BONUS:

    const [users, posts] = await Promise.all([
      fetchAxiosData("users"),
      fetchAxiosData("posts")
    ]);
    

    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