I try to get data from the backend and display that data in the frontend. This is the code that I wrote to do this task.
function ViewPost() {
const { id } = useParams();
console.log(id);
const [posts, setPosts] = useState({});
useEffect(()=>{
getOnePost();
}, []);
useEffect(()=>{
if (posts && posts.location) {
console.log(posts.location);
console.log(posts.location.longitude);
console.log(posts.location.latitude);
}
}, [posts]);
const getOnePost = async () => {
try {
const response = await axios.get(`/buyerGetOnePost/${id}`)
console.log(response);
const allPost=response.data.onePost;
setPosts(allPost);
} catch (error) {
console.error(`Error: ${error}`)
}
}
console.log(posts);
console.log(posts.wasteItemList);
return(
<div className="posts-b">
<div className="posts__container-b">
<h1>Post Details</h1>
<main className="grid-b">
{posts.wasteItemList.map((notes,index)=>(
<article>
<div className="text-b">
<h3>Post ID: {index+1}</h3>
<p>Waste Item: Polythene Roll</p>
<p>Quantity: 1 kg</p>
</div>
</article>
))}
</main>
</div>
</div>
);
}
export default ViewPost;
When I console.log(posts) it shows post data successfully. The wasteItemList is an array it has two objects.

When I console.log(posts.wasteItemList) it also shows the two array of objects successfully.

But the problems comes when I try to map wasteItemList. I tried to map using thisposts.wasteItemList.map. But I get an error 'TypeError: Cannot read property 'map' of undefined'. How do I solve this issue?
posts.wasteItemListis defined before trying to use.map()on it. When your component initially mounts and renders,postsis an empty object with nowasteitemListproperty (as defined by your initial state of{}). So trying to use.map()on it will throw an error