This is currently how my code looks
import React from 'react';
import './App.css';
class App extends React.Component {
state = {
apiData: []
}
render() {
console.log('api data is')
return (
<div>
<center>
<h1 id="title">hello something</h1></center>
<h1 id="date">{this.state.apiData.title}</h1>
</div>
)
}
componentDidMount() {
fetch('http://www.mocky.io/v2/5dece3d333000052002b9037')
.then(response => response.json())
.then(data => {
this.setState({
apiData: data
})
})
console.log("component fetched data")
}
}
export default App
I get this error when I try access something that has a value but when I do this
<h1 id="date">{this.state.apiData.date}</h1>
It works
not too sure how to fix as everything I have seen thus far is for data they have created through a const or let as opposed to fetching data from an API
apiData.title
is of type Object
, not an Array
of JSX children or strings.
You need to use apiData.title.rendered
, as shown in this snippet of response data from the API:
"title": {
"rendered": "Whatsapp and Facebook Messenger: how group chat is changing the dynamic of our friendships"
},
Try with a null check {this.state.apiData.title?.rendered}
Update: Try to open the link you're fetching the data from and follow the paths inside, for hero_image you need {this.state.apiData.acf?.hero_image.url}
As render fire before state set so you need to check before state update and use condition or && on "this.state.apiData.title" like this
class App extends React.Component { state = { apiData: [] } render() { console.log('api data is') return ( <div> <center> <h1 id="title">hello something</h1></center> <h1 id="date">{this.state.apiData.title && this.state.apiData.title.rendered}</h1> </div> ) } componentDidMount() { fetch('http://www.mocky.io/v2/5dece3d333000052002b9037').then(response => response.json()).then(data => { this.setState({ apiData: data }) }) console.log("component fetched data") } } ReactDOM.render( <App />, document.getElementById('root'));
<div id="root" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
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.