1️⃣ 설정
- axios 라이브러리 설치하기
$ cd api-integrate
$ yarn add axios
💡간단히 자주 사용되는 4가지 메서드 정리!
- GET : 데이터 조회
- POST : 데이터 등록
- PUT : 데이터 수정
- DELETE : 데이터 제거
2️⃣ axios 사용법 (GET)
import axios from 'axios';
axios.get('/users/1');
3️⃣ POST 사용법 ( 새로운 데이터 등록 )
- 두번째 파라미터에 등록하고자 하는 정보 넣기
axios.post('/users',{
username: 'blabla',
name: 'blabla'
});
💡useState와 useEffect로 데이터 로딩하기
- useState : 요청상태관리
- useEffect : 컴포넌트가 렌더링되는 시점에 요청을 시작
- 요청에 대한 3가지 상태관리
- 요청의 결과
- 로딩 상태
- 에러
Users.js
import React, {useState, useEffect} from 'react'
import axios from 'axios';
function Users() {
const [users, setUsers] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(()=>{
const fetchUsers = async()=>{
try{
// 요청이 시작 할 때에는 error와 users를 초기화
setError(null);
setUsers(null);
// loading 상태를 true로 바꾼다.
setLoading(true);
const response = await axios.get(
'api 문서의 주소!'
);
// 데이터는 response.data 안에 들어있다.
setUsers(response.data);
} catch (e) {
setError(e);
}
setLoading(false);
};
fetchUsers();
},[]);
if (loading) return <div>로딩중..</div> // 로딩이 활성화되었을 때
if (error) return <div>에러가 발생했습니다.</div>
if (!users) return null; //user 값이 아직 없을 때
return (
<ul>
{users.map(user=>{
<li key={user.id}>
{user.username} ({user.name});
</li>
})}
</ul>
)
}
export default Users
➕버튼을 눌러 API 재요청하기
<button onClick={fetchUsers}> 다시 불러오기 버튼 </button>
Reference
'React > API 연동' 카테고리의 다른 글
[React] #6 | Context 와 함께 사용하기 (0) | 2021.11.04 |
---|---|
[React] #5 | react-async, 요청 상태 관리하기 (0) | 2021.11.03 |
[React] #4 | useAsync 커스텀 Hook 만들어서 사용하기 (0) | 2021.11.03 |
[React] #3 | useReducer로 요청 상태 관리 (0) | 2021.11.03 |
[React] #1 | API 연동 (0) | 2021.11.03 |