Simply Rendering Data From Api
i'm trying my hardest to wrap my head around this concept and after wasting a couple hours i figured id try and see if someone would kindly fix and elaborate upon such a simple matter
constructor(props) {
super(props);
this.state = {
marketdata: [],
loading: true
}
}
componentDidMount() {
axios.get('https://api.coingecko.com/api/v3/global')
.then(res => res.data)
.then((data) => {
this.setState({ marketdata: data })
console.log(this.state.marketdata.data.market_cap_change_percentage_24h_usd)
})
}
...
render() {
const { coindata, marketdata} = this.state;
<p>{marketdata.data.market_cap_change_percentage_24h_usd}</p>
TypeError: Cannot read property 'market_cap_change_percentage_24h_usd' of undefined
i want to be able to better understand so i can carry on and not get stuck when trying to consume data from APIs throughout this entire project.
Answer
Not entirely sure what this.setState()
does, but I assume it should set the member state
.
The problem is that you try to access a member of an object while that object does not exist. So, you should change
this.state.marketdata.data.market_cap_change_percentage_24h_usd
to
this.state.marketdata.market_cap_change_percentage_24h_usd
{ marketdata: data }
does not mean that the new property is marketdata.data
but the colon (:
) is an assignment just like =
, so marketdata
gets the value of data
.
If that does not work try to console.log from "up to bottom" which means first log this.state
, then this.state.marketdata
and so on, until you see what you received and set.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM