I'm trying to use Strapi Headless CMS to create blog posts. I managed to fetch the JSON data but I'm unable to display it as HTML using the map() function. I want to display this data into the HTML but I keep getting this error. I already tried with a for loop and foreach() but I keep getting the same error like this or errorTypeError: Cannot read properties of undefined (reading 'data'). Here's my code so far:
const blogPosts = "http://localhost:1337/api/blogposts";
fetch(blogPosts)
.then((response) => {
return response.json();
})
.then((data) => console.log(data.data[0].attributes))
.then((data) => {
let posts = data;
posts.map(function (post) {
let body = document.createElement("div");
body.innerHTML = `${post.data.data[0].attributes.body}`;
li.appendChild(body);
});
})
.catch(function (err) {
console.log("error" err);
});
The JSON file looks like this:
{data: Array(1)
data: Array(1)
0:
attributes:
body: "text"
createdAt: "2022-02-11T10:29:48.930Z"
publishedAt: "2022-02-11T10:29:58.780Z"
updatedAt: "2022-02-11T10:29:58.790Z"
CodePudding user response:
Try to replace this line:
body.innerHTML = `${post.data.data[0].attributes.body}`;
with:
body.innerHTML = `${post.data[0].attributes.body}`;
CodePudding user response:
TypeError: Cannot read properties of undefined (reading 'data')
As error says, It is not able to read the data
property as you are having only one data
object in the response.
Valid JSON :
{
"data": [{
"attributes": {
"body": "text",
"createdAt": "2022-02-11T10:29:48.930Z",
"publishedAt": "2022-02-11T10:29:58.780Z",
"updatedAt": "2022-02-11T10:29:58.790Z"
}
}]
}
Hence, access it by calling data[0].attributes.body
instead of data.data[0].attributes.body
.