sharingStorage

React API 연동하기 2. useReducer로 요청상태 관리하기 본문

Front-End/React

React API 연동하기 2. useReducer로 요청상태 관리하기

Anstrengung 2023. 1. 11. 15:37

React API 연동하기 1번 과정에서 상태관리를 위해 사용했던 useState대신에 useReducer를 사용해보겠습니다.

 

useReducer를 사용했을 때의 좋은 점

1. useState의 setState 함수를 여러번 사용하지 않아도 돼서 코드의 길이가 짧아진다.

2. reducer로 로직을 분리하면 재사용이 용이하다.

 

결과 

User.js

import React, { useEffect, useReducer } from 'react';
import axios from 'axios';

const 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}`);
    }
};

const 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 (
        <div>
            <ul>
                {users.map((user) => (
                    <li key={user.id}>
                        {user.username} ({user.name})
                    </li>
                ))}
            </ul>
            <div>
                <button onClick={fetchUsers}>다시 불러오기</button>
            </div>
        </div>
    );
};
export default Users;

 

App.js 

import './App.css';
import Users from './Users.js';
import React from 'react';

const App = () => {
    return <Users></Users>;
};

export default App;

 

 

출처 :

Comments