API 연동하기
[React/리액트] API 연동하기 CRA로 프로젝트 폴더를 생성하고, API를 호출하기 위해서 axios 라는 라이브러리를 설치해준다. npx create-react-app api-integrate cd api-integrate yarn add axios axios를 사..
devts.tistory.com
이전에 구현했던 User 컴포넌트에서 useState
대신에 useReducer
를 사용해서 구현해보고자 한다.
useReducer
를 사용해서 LOADING, SUCCESS, ERROR 액션에 따라 다르게 처리를 해보려고 한다.
useReducer
로 구현했을 때의 장점은 useState
의 setState
함수를 여러번 사용하지 않아도 된다는 점과,
리듀서로 로직을 분리했으니 다른곳에서도 쉽게 재사용할 수 있다는 점이다.
물론, 취향에 따라 useState
로 구현을 해도 무방하다.
Users.js
import React, { useEffect, useReducer } from "react";
import axios from "axios";
// LOADING, SUCCESS, ERROR 액션을 관리하는 Reducer 함수 생성
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:
throw new Error(`Unhandled action type: ${action.type}`);
}
}
function Users() {
const [state, dispatch] = useReducer(reducer, {
loading: false,
data: null,
error: null,
});
// reducer 함수에서 작성해준 액션들을 fetchUsers 함수에 dispatch 해주면 된다.
const fetchUsers = async () => {
dispatch({ type: "LOADING" });
try {
const response = await axios.get(
"http://jsonplaceholder.typicode.com/users/"
);
dispatch({ type: "SUCCESS", data: response.data });
} catch (e) {
dispatch({ type: "ERROR", error: e });
}
};
// 컴포넌트가 처음 렌더링될 때 실행될 작업: useEffect 함수 두번째 파라미터에 빈 배열
// 컴포넌트가 처음 렌더링 될 때 fetchUsers 함수가 렌더링 됨.
useEffect(() => {
fetchUsers();
}, []);
// users, loading, error 3가지 상태에 따라 다른 결과물을 반환하도록 설정
const { loading, error, data: users } = state;
if (loading) return <div>로딩중..</div>;
if (error) return <div>에러가 발생했습니다</div>;
if (!users) return null;
return (
<>
<ul>
{users.map((user) => (
<li key={user.id}>
{user.username} ({user.name})
</li>
))}
</ul>
<button onClick={fetchUsers}>다시 불러오기</button>
</>
);
}
export default Users;