React 와 API request

nona·2021년 1월 8일
0

React

목록 보기
1/7
post-thumbnail

Javascript에서 fetch를 이용하여 Get request를 보내는 것만 해보다가 오늘은 React에서 API request를 하는 날이다! 두근두근. 과연 리액트에서는 뭐가 어떻게 다를까? 😃

오늘의 목표 : 유저가 검색창에 특정키워드를 검색했을때 우리가 AJAX request를 만들어서 unsplash API에게 보내고 JSON를 받아오자. 그리고 화면에 render 해버려!

  • 사용한 링크: unsplash.com/developers

axios VS fetch

AJAX Request를 위해서 리액트에서는 보통 이 두가지 방법을 많이 씀

  1. axios: npm을 이용해서 리액트 프로젝트에 쉽게 설치할 수 있는 라이브러리로, 따로 분리되어 있는 패키지이다.
  2. fetch: 라이브러리가 아닌 function으로 axios처럼 따로 분리되어 있는게 아니다. 모던 브라우저에 이미 지어져 있는 function. 그래서 따로 패키지를 설치할 필요가 없다.

그럼 리액트 앱에서는 무엇을 쓰는게 더 좋을까?

axios를 쓰는게 더 좋은데 이유는, fetch를 쓰면 axios에서는 이미 내장되어 있는 많은 코드들을 직접 써야하기 때문이다.
또한 axios는 좀 더 예상 가능한 방향으로 네트워크 리퀘스트를 다루기 때문에 프로패셔널하게 쓰기가 좋다.

axios 설치 command

npm install --save axios

axios import 하기

/* App.js (third party package나 dependency들은 연결된 파일들보다 
윗줄에 import하는게 convention이다) */
import axios from 'axios';

axios 사용법

axios.get 은 두가지 argument를 받는다. 하나는 우리가 GET 리퀘스트를 보낼 주소, 나머지 하나는 그 리퀘스트를 customize할 수 있는 코드들을 넣는다.

class App extends React.Component {
  onSearchSubmit(term) {
    axios.get('https://api.unsplash.com/search/photos', {
      params: { query: term },
      headers: {
        Authorization:
          'Client-ID xKtQ6HWW2cUFgoYVQgVdxr1BwqZjg4f_yNFZ8rjb5FY'
      }
    });
  }

두번째 argument들을 살펴보자.
params: { query: term } <- 유저의 서치키워드를 받아서 사용할 수 있게 해준다. term이 onSearchSubmit Function을 통해서 유저에게서 받는 키워드.
이게 붙으면서 결국 url이 https://api.unsplash.com/search/photos?query=term 요런식으로 되는거임.

headers: {Authorization: } <- unsplash API에 접근할 수 있는 키

AJAX Request가 끝났을때 알려주는 method를 추가

두가지 방법이 있다
1. .then 사용 -> promise를 사용할때 사용가능

class App extends React.Component {
  onSearchSubmit(term) {
    axios.get('https://api.unsplash.com/search/photos', {
      params: { query: term },
      headers: {
        Authorization:
          'Client-ID xKtQ6HWW2cUFgoYVQgVdxr1BwqZjg4f_yNFZ8rjb5FY'
      }
    }).then((response => {
    	console.log(response.data.results);
    });
  }
  1. async await 문법 사용
    : async 키워드를 method이름 앞에 추가하고, return되는 것 앞에(혹은 무엇이든 결과를 보기까지 약간의 시간이 걸리는 것 앞에) await 키워드를 붙인다. -> 그 후에 변수에 선언
class App extends React.Component {
  async onSearchSubmit(term) {
    const response = await axios.get('https://api.unsplash.com/search/photos', {
      params: { query: term },
      headers: {
        Authorization:
          'Client-ID xKtQ6HWW2cUFgoYVQgVdxr1BwqZjg4f_yNFZ8rjb5FY'
      }
    });
   
   console.log(response.data.results);
  }

이렇게 받은 response를 component state에 넣기

class App extends React.Component {
  state = { images: [] };
  async onSearchSubmit(term) {
   const response = await axios.get('https://api.unsplash.com/search/photos', {
      params: { query: term },
      headers: {
        Authorization:
          'Client-ID xKtQ6HWW2cUFgoYVQgVdxr1BwqZjg4f_yNFZ8rjb5FY'
      }
    });
   
 this.setState({ images: response.data.results });
  }


render() {
  return (
    <div className="ui container" style={{ marginTop: '10px'}}>
    <SearchBar onSubmit={this.onSearchSubmit}/>
	<ImageList images={this.state.images}/>
     </div>
    );
  }
}
  1. state initialize with array (state의 디폴트는 null이 아닌 array로 하는게 좋음)
  2. setState로 state 업데이트하기

Refactoring

  1. 에러 방지를 위해 onSearchSubmit을 arrow function으로 바꿔준다.
  2. unsplash component를 따로 빼서 코드를 정리한다.
// unsplash.js
import axios from 'axios';

export default axios.create ({
  baseURL: 'https://api.unsplash.com',
  headers: {
    Authorization:
      'Client-ID xKtQ6HWW2cUFgoYVQgVdxr1BwqZjg4f_yNFZ8rjb5FY'
  }
});
//App.js
import React from 'react';
import unsplash from '../api/unsplash';

class App extends React.Component {
  state = { images: [] };
  onSearchSubmit = async (term) => {
    const response = await unsplash.get('/search/photos', {
      params: { query: term }
    });
   
     this.setState({ images: response.data.results });
  };

  render() {
    return (
      <div className="ui container" style={{ marginTop: '10px'}}>
      <SearchBar onSubmit={this.onSearchSubmit}/>
      <ImageList images={this.state.images}/>
      </div>
    );
  }
}

export default App;

useEffect로 data fetching 하기

import React, { useState, useEffect } from 'react';
const UseEffectApi = () => {
  const [user, setUsers] = useState([]);
  
  const getUsers = async() => {
      const response = await get('https://api.github.com/users');
      const users = await response.json();
      setUsers(users);
  };
  
  useEffect(()=> {
  	getUsers();
  },[])
  
  return (
    {users.map((user)=> {
  
  }}
  )
};

functional component와 API fetching

const fetchRandomData = () => {
  return axios.get('https://randomuser.me/api'
  }.then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
}
       ```
끝!
자바스크립트로 AJAX 을 할때에는 fetch만 썼었는데 새로 axios를 알게된게 즐겁다! fetch에서 발생할 수 있는 몇몇 예상치 못한 결과들도 axios에서는 다 잡아준다고 하니 앞으로 쓸면서 그런 차이점들을 발견할때마다 또 놀랄듯 ❤

0개의 댓글