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
I think you’re repeating
index
twice when it should bepost
instead:It looks like you just need to add
return
to the map function.