deVSner

componentDidMount async/await 함께 쓰기 본문

카테고리 없음

componentDidMount async/await 함께 쓰기

RudeofSun 2020. 7. 7. 13:56

 

 

프로젝트를 하면서 훅스 문법이 아닌,

클래스형 컴포넌트로 리액트를 구성하고 있다.

그러다보니, axios를 어떻게 줘야 하나...그 형태가 긴가민가했었다.

 

아래와 같은 자료를 찾았다!!!

 

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  constructor() {
    super();
    this.state = { data: [] };
  }

  async componentDidMount() {
    const response = await fetch(`https://api.coinmarketcap.com/v1/ticker/?limit=10`);
    const json = await response.json();
    this.setState({ data: json });
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.data.map(el => (
            <li>
              {el.name}: {el.price_usd}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

export default App;

ReactDOM.render(<App />, document.getElementById("app"));