AJAX Request를 위해서 리액트에서는 보통 이 두가지 방법을 많이 씀
- axios: npm을 이용해서 리액트 프로젝트에 쉽게 설치할 수 있는 라이브러리로, 따로 분리되어 있는 패키지이다.
- fetch: 라이브러리가 아닌 function으로 axios처럼 따로 분리되어 있는게 아니다. 모던 브라우저에 이미 지어져 있는 function. 그래서 따로 패키지를 설치할 필요가 없다.
그럼 리액트 앱에서는 무엇을 쓰는게 더 좋을까?
axios를 쓰는게 더 좋은데 이유는, fetch를 쓰면 axios에서는 이미 내장되어 있는 많은 코드들을 직접 써야하기 때문이다.
또한 axios는 좀 더 예상 가능한 방향으로 네트워크 리퀘스트를 다루기 때문에 프로패셔널하게 쓰기가 좋다.
npm install --save axios
/* App.js (third party package나 dependency들은 연결된 파일들보다
윗줄에 import하는게 convention이다) */
import axios from '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에 접근할 수 있는 키
두가지 방법이 있다
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);
});
}
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);
}
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>
);
}
}
// 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;
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)=> {
}}
)
};
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에서는 다 잡아준다고 하니 앞으로 쓸면서 그런 차이점들을 발견할때마다 또 놀랄듯 ❤