1

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;

1 Answer 1

1

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>
))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.