JS Library/React

useReducer 요청 상태 관리

원2 2022. 6. 9. 06:03
728x90
반응형

useReducer 의 장점

로직 분리로 인해 다른곳에서도 재사용 가능

import React, { useEffect, useReducer, useState } 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, dispacth] = useReducer(reducer, {
        loading: false,
        data: null,
        error: null
    });
    const [name, setName] = useState('Leanne Graham');
    const [list, setList] = useState();

    const fetchUsers = async () => {
        dispacth({ type: 'LOADING' });
        try {
            const response = await axios.get(
                'https://jsonplaceholder.typicode.com/users'
            );
            dispacth({ type: 'SUCCESS', data: response.data });
        } catch (e) {
            dispacth({ type: 'ERROR', error: e });
        }
    };

    useEffect(() => {
        fetchUsers();
    }, []);

    const { loading, data: users, error } = 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;
728x90
반응형

'JS Library > React' 카테고리의 다른 글

react-icons link  (0) 2022.08.01
CSS Module  (0) 2022.08.01
Sass  (0) 2022.08.01
API 연동하기, axios  (0) 2022.06.09
Immer 라이브러리  (0) 2022.05.26
Context API 전역 값 관리  (0) 2022.05.26