Reputation: 83
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?
Upvotes: 2
Views: 805
Reputation: 3019
This happens because the data is not available immediately so, for a while posts.wasteItemList
is undefined.
Whenever accessing wasteItemList
you should use
posts && posts.wasteItemList && posts.wasteItemList.map(()=> *)
This gives you the complete safety.
If you are using TypeScript or node version >= 14, then you can use optional chaining
.
posts?.wasteItemList?.map(()=>{})
Which is basically the same thing just more syntactically pleasing.
Upvotes: 3
Reputation: 20821
The initial value of posts
is {}
, so there is no wasteItemList
property on posts.
Attempting to access posts.wasteItemList
would return undefined
and you cannot map over undefined
.
Try using optional chaining on posts?.wasteItemList?.map
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>
);
Upvotes: 1
Reputation: 1227
Change this particular line
{posts.wasteItemList.map((notes,index)=>
to
{posts.wasteItemList && posts.wasteItemList.map((notes,index)=>
Upvotes: 1