Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue rendering list in React Component using API

The code below is a component I am using to show the title of the posts based on what I get from the link. Everything with the API seems to work well, but I am not getting the list rendered for posts.forEach(post => <li id={post.id}> {post.title} </li>. Can anyone know how can I render the post title as a list from an array posts I get from an API? Thank You for helping, and let me know if you need more information.

import React, { useState, useEffect } from "react";
import axios from "axios";

const DataFetch = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then((res) => {
        setPosts(res.data);
        console.log(posts[0].title);
      })
      .catch((err) => console.log(err));
  }, []);

  return <ul>
    {  posts.forEach(post => <li id={post.id}> {post.title} </li> )}
  </ul>
};

export default DataFetch;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Array.prototype.forEach is a void return. You want to map the posts to JSX. Don’t forget to also map a React key.

posts.map(post => (
  <li key={post.id} id={post.id}>
    {post.title}
  </li>
))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading