데이터 가져오기

Fetch API 대 Axios 1

fetch API에는 두어 가지의 gotcha가 있습니다. response로부터 JSON을 추출하는 별도의 단계가 있어야 합니다. 에러를 모두 잡지도 못합니다. 예를 들어, 404는 일반 response로써 반환될 것입니다. 여러분은 response 코드를 확인해야 하고, 앞으로 포착될 네트워크 에러를 처리해야 합니다.

그러니까 두 군데에서 에러를 처리해야 합니다. 하지만 여러분은 이러한 이슈를 다루는 데 axios.js 라이브러리를 이용하고, 외부 dependency를 추가하는 값으로 좀 더 정교한 코드를 손에 넣을 수 있습니다.

fetchQuotes = () => {
  this.setState({...this.state, isFetching: true})
  axios.get(QUOTE_SERVICE_URL)
    .then(response => this.setState({quotes: response.data,
                                     isFetching: false}))
    .catch(e => console.log(e);
}

양이 많지 않아 보이지만 유용합니다. 새 인용문을 추가하는 코드는 axios로 훨씬 정밀해집니다. 아래는 fetch 버전입니다.

handleSubmitWithFetch = event => {
  let data = new FormData()
  data.append('quote', this.state.quote)
  fetch(this.props.quote_service_url,
        {method: 'POST', body: data})
    .then(response => response.json())
    .catch(e => console.log(e));

  event.preventDefault();
}

아래는 axios 버전입니다.

handleSubmit = event => {
  axios.post(this.props.quote_service_url,
             {'quote': this.state.quote})
    .then(r => console.log(r))
    .catch(e => console.log(e));

  event.preventDefault();
}

참고 사이트

1

React 애플리케이션에서 데이터 불러오기: https://code.tutsplus.com/ko/tutorials/fetching-data-in-your-react-application–cms-30670