Async Fetch data
by Allie Yu
HTML
<div id="app"></div>
<!-- https://www.valentinog.com/blog/how-async-await-in-react/#How_To_Use_Async_Await_in_React_what_is_asyncawait -->
React
class App extends React.Component {
constructor() {
super();
this.state = { data: [] };
}
async componentDidMount() {
try{
const response = await fetch(`https://api.coinmarketcap.com/v1/ticker/?limit=10`);
if (!response.ok) {
throw Error(response.statusText);
}
const json = await response.json();
this.setState({ data: json });
} catch (error) {
console.log(error);
}
}
render() {
return (
<div>
<ul>
{this.state.data.map((el,key) => (
<li key={key}>
{el.name}: {el.price_usd}
</li>
))}
</ul>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));