skip to Main Content

I’m fetching a list of objects.
Using map function should display a list but there wasn’t. I checked if it was saved to ‘useState’ via console.log(posts), and yes there was a list of objects. My only problem is I cant display it to the browser. Also, I already attached the necessary scripts for ‘react’, ‘reactDOM’, and ‘babel’.

{% extends "network/layout.html" %} {% block body %}
<div id="index"></div>

<script type="text/babel">
  const AllPosts = () => {
    const [posts, setPosts] = React.useState([]);
    React.useEffect(() => {
      fetch("/allposts")
        .then((response) => response.json())
        .then((data) => {
          setPosts(data.posts);
        })
        .catch((error) => {
          console.error(error);
        });
    }, []);

    return (
      <ul>
        {posts &&
          posts.map((post, index) => {
            <li key={index}>{`Try ${index}`}</li>;
          })}
      </ul>
    );
  };

  const Index = () => {
    return <AllPosts />;
  };

  const container = document.getElementById("index");
  const root = ReactDOM.createRoot(container);
  root.render(<Index />);
</script>

{% endblock %}

I wanted to return each object on the list in an li tag, however, there was no data when I inspected it on the browser.

2

Answers


  1. I think you’re repeating index twice when it should be post instead:

    return (
              <ul>
                {posts &&
                  posts.map((index, post) => {
                    <li key={index}>{`Try ${post}`}</li>;
                  })}
              </ul>
    
    Login or Signup to reply.
  2. It looks like you just need to add return to the map function.

    posts.map((post, index) => {
      return <li key={index}>{`Try ${index}`}</li>;
    })}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search