I am working on react app Everything works fine but when I hit localhost endpoint I get Array of my stored document in mongodb so I wanna use map to create loop and for that I have to also pass key to the each child but how to perform this all,I am facing destructuring problem , I mean I am unable to do ,
my function to hit localhost is below
import React, { useEffect } from "react";
// import PostContext from '../context/posts/postContext'
import Footer from "./Footer";
import Post from "./Post";
import Sidebar from "./Sidebar";
const Posts = () => {
const getAllPost = async () => {
const response = await fetch("http://localhost:5000/allposts", {
method: "GET",
});
const data = await response.json();
console.log(data);
};
useEffect(() => {
getAllPost();
}, []);
return (
<>
<main className="main">
<div className="container">
<h4 className="heading">Posts</h4>
<Post key={} />
</div>
<div className="sidebar">
<h4 className="heading">Sidebar</h4>
<Sidebar />
</div>
</main>
<footer>
<Footer />
</footer>
</>
);
};
export default Posts;
I also want to write title to get title not this.that.title please give me solution to handle this
first, create a state to store data const [posts,setPosts]=useState([]). then
write this code in getAllPost() function, setPosts(data) to store data you receive from API into state. Now go to html code, below <>h4</> tags and write this {posts.map((post,index)=><Post key={index} post={post}>)}. Then you can access post from props of <Post/> component.
Edit: i assume your response from API is already an Array