axios는 현재 가장 많이 사용하고 있는 자바스크립트 HTTP 클라이언트이다.
이 라이브러리의 특징은 HTTP요청을 Promise기반으로 처리한다는 점이다.
$ yarn create react-app news-viewer
$ cd news-viewer
$ yarn add axios
리액트 프로젝트를 생성하고 axios를 설치해보자.
// App.js
import React, { useState } from "react";
import axios from "axios";
function App() {
const [data, setData] = useState(null);
const onClick = () => {
axios
.get("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => {
setData(response.data);
});
};
return (
<div>
<div>
<button onClick={onClick}>불러오기</button>
</div>
{data && (
<textarea
rows={7}
value={JSON.stringify(data, null, 2)}
readOnly={true}
/>
)}
</div>
);
}
export default App;
불러오기 버튼을 누르면 JSONPlaceholder(https://jsonplaceholder.typicode.com/)에서 제공하는 가짜 API를 호출하고 그에 대한 응답을 컴포넌트 상태에 넣어서 보여주는 예제이다.
onClick함수에서 axios.get함수를 사용하였다.
파라미터로 전달된 주소에 GET 요청을 해준다.
이에 대한 결과를 .then을 통해 비동기적으로 확인할 수 있다.
위 코드에 async를 적용하면 다음과 같다.
// App.js
import React, { useState } from "react";
import axios from "axios";
function App() {
const [data, setData] = useState(null);
const onClick = async () => {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/todos/1"
);
setData(response.data);
} catch (e) {
console.log(e);
}
};
return (
<div>
<div>
<button onClick={onClick}>불러오기</button>
</div>
{data && (
<textarea
rows={7}
value={JSON.stringify(data, null, 2)}
readOnly={true}
/>
)}
</div>
);
}
export default App;