[React] API 연동하기
https://axios-http.com/kr/docs/intro
시작하기 | Axios Docs
시작하기 브라우저와 node.js에서 사용할 수 있는 Promise 기반 HTTP 클라이언트 라이브러리 Axios란? Axios는 node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트 입니다. 그것은 동형 입니다(동일한 코
axios-http.com
https://jsonplaceholder.typicode.com/
JSONPlaceholder - Free Fake REST API
{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. As of Oct 2021, serving ~1.7 billion requests each month.
jsonplaceholder.typicode.com
axios 라이브러리
터미널에 npm install axios 입력 !
axios 사용해서 get, put, post, delete 등의 메서드로 API 요청함
rest API
get: 데이터 조회
post: 데이터 등록
put: 데이터 수정
delete: 데이터 제거
axios 사용법
import axios from 'axios';
데이터 조회
사용법> axios.get(경로)
ex> axios.get('/users/1');
데이터 등록
사용법> axios.post(경로, 데이터정보)
ex> axios.post('/users/', {
username: "green",
name: "aaaa"
})
useState와 useEffect로 데이터 로딩하기
useState 요청 상태를 관리
1. 요청의 결과
2. 로딩상태
3. 에러
useEffect 컴포넌트가 랜더링 되는 시점에 요청을 시작
App.js
import './App.css';
import Posts from './components/Posts';
import PostsReducer from './components/PostsReducer';
import Users from './components/Users';
import UsersReducer from './components/UsersReducer';
function App() {
return (
<div className="App">
<Users/>
<UsersReducer/>
<Posts/>
<PostsReducer/>
</div>
);
}
export default App;
components/Users.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const Users = (props) => {
// 상태관리
// 1. 요청의 결과
// 2. 로딩상태
// 3. 에러
const [ users, setUsers ] = useState(null);
const [ loading, setLoading ] = useState(false);
const [ error, setError ] = useState(null);
const fetchUsers = async () => {
try {
// 요청이 시작될 때, error와 users를 초기화
setError(null);
setUsers(null);
// loading상태를 true로 변경
setLoading(true);
// 요청한 데이터는 response.data안에 있습니다.
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
setUsers(response.data);
}
catch(e) {
setError(e);
}
setLoading(false);
}
// useEffect(()=>{},[])
useEffect(()=>{
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>
<button onClick={fetchUsers}>다시 불러오기</button>
</div>
);
};
export default Users;
components/UsersReducer.js
import React, { useReducer, useEffect } from 'react';
import axios from 'axios';
// 초기값, reducer 함수생성
// 초기값: loading, data, error
const initialState = {
loading: false,
data: null,
error: null
}
function reducer(state, action){
switch(action.type){
case 'LOADING':
return{
loading: true,
data: null,
error: null
};
case 'SUCCESS':
return {
loading: false,
data: action.data,
error: null
};
case 'ERROR':
return {
loading: false,
data: null,
error: action.error
};
default:
return state;
}
}
const UsersReducer = (props) => {
const [ state, dispatch] = useReducer(reducer, initialState);
const fetchUsers = async () => {
dispatch({type: "LOADING"});
try{
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
dispatch({ type:'SUCCESS', data:response.data });
}
catch(e) {
dispatch({type: 'ERROR', error: e})
}
}
useEffect(()=>{
fetchUsers();
}, []);
const { loading, data, error } = state;
if(loading) return <div>로딩중...</div>
if(error) return <div>에러가 발생했습니다.</div>
if(!data) return null
return (
<div>
<ul>
{data.map(user => (
<li key={user.id}>
{user.username} ({user.name})
</li>
)
)}
</ul>
<button onClick={fetchUsers}>다시 불러오기</button>
</div>
);
};
export default UsersReducer;
components/Posts.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const Posts = (props) => {
const [ posts, setPosts ] = useState(null);
const [ loading, setLoading ] = useState(false);
const [ error, setError ] = useState(null);
const fetchPosts = async () => {
try {
setError(null);
setPosts(null);
setLoading(true);
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
setPosts(response.data);
}
catch(e) {
setError(e);
}
setLoading(false);
}
useEffect(()=>{
fetchPosts();
}, [])
if(loading) return <div>로딩중 ...</div>
if(error) return <div>에러가 발생했습니다.</div>
if(!posts) return null;
return (
<div>
<table>
<thead>
<tr>
<th>id</th>
<th>title</th>
<th>body</th>
</tr>
</thead>
<tbody>
{posts.map(post=>(
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
<td>{post.body}</td>
</tr>
))}
</tbody>
</table>
<button onClick={fetchPosts}>다시 불러오기</button>
</div>
);
};
export default Posts;
components/PostsReducer.js
import React, { useReducer, useEffect } from 'react';
import axios from 'axios';
const initialState= {
loading: false,
data: null,
error: null
}
function reducer(state, action) {
switch(action.type) {
case 'LOADING' :
return {
loading: true,
data: null,
error: null
};
case 'SUCCESS':
return {
loading: false,
data: action.data,
error: null
};
case 'ERROR':
return {
loading: false,
data: null,
error: action.error
};
default:
return state;
}
}
const PostsReducer = (props) => {
const [state, dispatch ] = useReducer(reducer, initialState);
const fetchPosts = async () => {
dispatch({type: "LOADING"});
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
dispatch({ type:'SUCCESS', data:response.data });
}
catch(e) {
dispatch({type: "ERROR", error: e});
}
}
useEffect(()=>{
fetchPosts();
}, []);
const {loading, data, error} = state;
if(loading) return <div>로딩중...</div>
if(error) return <div>에러가 발생했습니다.</div>
if(!data) return null
return (
<div>
<table>
<thead>
<tr>
<th>id</th>
<th>title</th>
<th>body</th>
</tr>
</thead>
<tbody>
{data.map(post=>(
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
<td>{post.body}</td>
</tr>
))}
</tbody>
</table>
<button onClick={fetchPosts}>다시 불러오기</button>
</div>
);
};
export default PostsReducer;
.
.
.
2022.06.29 - [Coding/React] - [React] API 연동하기 2