I am fetching json data from the public folder's Blog.json file, but the state is returning an array within an array and I'm unable to fetch the data I need.
here is my code:
export default class BlogPage extends React.Component {
constructor(props) {
super(props);
this.state = {
resultsLoaded: true,
blogs: [],
error: null
}
}
componentDidMount = () => {
fetch('./Blog.json')
.then(res => res.json())
.then(
(result) => {
let blogArray = Object.values(result);
this.setState({
resultsLoaded: true,
blogs: blogArray
})
return blogArray
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const {error, resultsLoaded, blogs} = this.state;
if (error) {
return (
<div>Error: {error.message}</div>
);
} else if (!resultsLoaded) {
return (
<div>Loading.....</div>
);
} else {
console.log(this.state);
let blogResults = blogs.map((e, index) => (
<div>
<h3>Working!</h3>
<p>{e.title}</p>
</div>
))
return (
<div>{blogResults}</div>
);
}
}
}
My JSON file looks like this:
{
"data": [
{
"id": "1",
"title": "Work Ethic",
"post": "Lorem ipsum dolor sit amet...",
"image": "",
"date": ""
},
{
"id": "2",
"title": "Impostor Syndrome",
"post": "Lorem ipsum dolor sit amet...",
"image": "",
"date": ""
},
{
"id": "3",
"title": "Getting Hired",
"post": "Lorem ipsum dolor sit amet...",
"image": "",
"date": ""
}
]
}
This image is what is logged in the console:
Also, I am getting the following error: "Each child in a list should have a unique "key" prop.", and {e.title} doesn't display. I'm guessing due to the array error.
Thanks.
In react each item inside a loop should have a key
please refer this
so
let blogResults = blogs.map((e, index) => (
<div key={index}>
<h3>Working!</h3>
<p>{e.title}</p>
</div>))
return (<div>{blogResults}</div>);
regarding the {e.title} not showing value issue, please check the object has that particular key.
For your key warning, do like this: <div key={index}>
in your immediate div tag under map
method.
For the other problem can you post your JSON file?
Most probably your Object.values
is doing this problem. In result if you have something like this: {blogs: [{...}, {...}, {...}]} then obviously your Object.values will behave like this. If you want your intended behaviour then you should write something like let blogsArr = results.blogs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.