- Today
- Total
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- js
- Angular
- deep dive
- 자바스크립트
- 네트워크
- JavaScript
- map
- async
- C++
- 모던 자바스크립트
- React
- http
- 모던 자바스크립트 deep dive
- html
- 백준 실버
- 그림으로 배우는 http&network
- 에러처리
- Java Script
- get
- 프론트엔드
- 백준
- 상태관리
- git
- 비동기
- 이터러블
- 알고리즘
- error
- 웹
- es6
- git error
Archives
sharingStorage
React API 연동하기 1. React API 사용해보기 본문
1.React에서 API를 사용해보기
1.1 API 연동의 기본
API연동을 위해서 우선 새 프로젝트를 만들어야 한다.
npx create-react-app react-api-use
API를 호출하기 위해서 axios 라는 라이브러리를 설치한다.
cd react-api-use
npm install yarn
// yarn add axios
axios를 사용하여 GET, PUT, POST, DELETE 등의 메서드로 API요청을 할 수 있다.
API연동 실습에는 JSONPlaceholder 에 있는 연습용 API를 사용해볼 것이며
API는 https://jsonplaceholder.typicode.com/users 주소이다.
결과물
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
(...)
]
2. useState와 useEffect로 사용
useState로 요청상태를 관리하고, useEffect로 컴포넌트가 렌더링되는 시점에 요청을 시작하는 작업을 해본다.
Users.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const Users = () => {
const [users, setUsers] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const fetchUsers = async () => {
try {
// 요청이 시작할 때에는 error와 user를 초기화하고 loading의 상태를 true로 바꾼다.
setError(null);
setUsers(null);
setLoading(true);
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
setUsers(response.data); //data는 response 안에 들어있다.
console.log(response.data);
} catch (e) {
setError(e);
}
setLoading(false);
};
fetchUsers();
}, []);
if (loading) return <div>로딩중 ...</div>;
if (error) return <div>에러 발생</div>;
if (!users) return null;
return (
<div>
<ul>
{users.map((user) => (
<li key={user.id}>
{user.username} ({user.name})
</li>
))}
</ul>
</div>
);
};
export default Users;
useEffect에 첫 번째 파라미터로 등록하는 함수는 비동기함수를 사용할 수 없으므로(async 사용 불가) 함수 내부에서 async를 사용해야한다.
App.js
import './App.css';
import Users from './Users.js';
import React from 'react';
const App = () => {
return <Users></Users>;
};
export default App;
결과
출처
'Front-End > React' 카테고리의 다른 글
React18 new Hooks (5) | 2023.12.07 |
---|---|
React custom hooks : what, how, when, why (5) | 2023.11.16 |
React query와 Asyncronous Recoil (feat Suspense, Loadable) (8) | 2023.05.08 |
Create React App환경에서 이미지 불러오는 방법(public vs src) (0) | 2023.01.25 |
React API 연동하기 2. useReducer로 요청상태 관리하기 (2) | 2023.01.11 |
Comments