728x90
반응형
이번에는 useState 대신에 useReducer로 구현해보도록 하겠다.
Users.js
import React, { useEffect, useReducer } from 'react';
import axios from 'axios';
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
});
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: users, error } = state; // state.data 를 users 키워드로 조회
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;
useReducer 로 구현했을 때의 장점은 useState를 여러번 사용하지 않아도 되며 로직을 분리했으니 다른곳에서도 쉽게 재사용을 할 수 있다는 점이다.
728x90
반응형
'Front-End > React.js' 카테고리의 다른 글
React.js | API 연동 | react-async로 요청 상태 관리하기 (0) | 2021.10.07 |
---|---|
React.js | API 연동 | useAsync 커스텀 Hook (0) | 2021.10.07 |
React.js | API 연동 | 기본 (0) | 2021.10.07 |
React.js | 입문 | Immer (0) | 2021.09.17 |
React.js | 입문 | Context API 전역 값 관리(2) (0) | 2021.09.17 |