'Unhandled Rejection (TypeError): Cannot read property 'map' of undefined .......cant get all posts
Problem: The web page is not loading and showing an error(below).
Frontend part:
import React, { useEffect, useState } from "react";
const Read = () => {
const [data, setdata] = useState([]);
useEffect(() => {
fetch("/allpost", {
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
.then(res => res.json())
.then(result => {
console.log(result);
setdata(result.posts);
});
});
return (
<div className="bg">
<h2>Welcome to Confessions</h2>
{data.map(posts => {
return (
<div className="confession">
<div className="title">
<h3>{posts.heading}</h3>
</div>
<div className="body">
<p>{posts.confess} </p>
</div>
</div>
);
})}
</div>
);
};
export default Read;
posts is an object.
Backend part:
router.get("/allpost", authenticate, async (req, res) => {
try {
const posts = await Post.find({});
res.status(200).json(posts);
} catch (err) {
res.status(500).json(err);
}
});
Unable to get data on postman also. I even cant get posts on postman...
Postman error:
{
"stringValue": "\"allpost\"",
"valueType": "string",
"kind": "ObjectId",
"value": "allpost",
"path": "_id",
"reason": {},
"name": "CastError",
"message": "Cast to ObjectId failed for value \"allpost\" (type string) at path \"_id\" for model \"USER\""
}
ERROR on the web page:
Unhandled Rejection (TypeError): Cannot read property 'map' of undefined
Read
src/components/Read.js:106
103 |
104 | return (
105 | <div className="bg">
> 106 | <h2>Welcome to Confessions</h2>
| ^ 107 |
108 | {
109 | data.map(posts=>{
View compiled
▶ 18 stack frames were collapsed.
(anonymous function)
src/components/Read.js:48
45 | }).then(res=>res.json())
46 | .then(result=>{
47 | console.log(result)
> 48 | setdata(result.posts)
| ^ 49 | })
50 | })
51 |
What's the correct way to write the .map function for the object.
Please help, it's been a whole day with this problem.
Solution 1:[1]
It looks like your endpoint is inside a router so it'll get prefixed with whatever you prefixed it inside your server.js/index.js as it is commonly named on the backend.
You are trying to fetch data from /allpost but i suspect the endpoint might be a bit different.
A look at your server entry point where you initialize your express app would help identify the underlying cause for this error.
Solution 2:[2]
I will just address your client side error in my answer. The server side error ( Cast to ObjectId failed for value \"allpost\") is the initial cause of your problem, but you also write your client side code so that it will handle error responses from the backend api without crashing.
When using the fetch api, 400 and 500 responses will not throw an error (result in a rejected promise). You have to do that yourself by checking the response.ok property. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#checking_that_the_fetch_was_successful
In your case, the api error will return a HTTP response with a 500 status code (error) and a valid json body. So your res.json() works fine.
useEffect(() => {
fetch('/allpost', {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
}).then(response => {
// A 400 or 500 response from the server should throw an error.
if (response.ok) return response.json()
else throw new Error('Server error: ' + response.text())
})
.then(result => {
// This function will only run if the previous step did not throw an error
console.log(result)
setdata(result.posts)
})
})
Solution 3:[3]
Add error handlers in Read.js file
import React, { useEffect, useState } from "react";
const Read = () => {
const [data, setdata] = useState([]);
useEffect(() => {
fetch("/allpost", {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((result) => {
console.log(result);
setdata(result.posts);
});
});
return (
<div className="bg">
<h2>Welcome to Confessions</h2>
{data && data.length
? data.map((posts) => {
return (
<div className="confession">
<div className="title">
<h3>{posts.heading}</h3>
</div>
<div className="body">
<p>{posts.confess} </p>
</div>
</div>
);
})
: null}
</div>
);
};
export default Read;
Solution 4:[4]
You can copy the iOS Simulator from Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes to /Library/Developer/CoreSimulator/Profiles/Runtimes
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dandan Drori |
| Solution 2 | |
| Solution 3 | Isuru Chandrasiri |
| Solution 4 | Jeremy Huddleston Sequoia |
