[React] API 연동하기 2

2022. 6. 29. 12:09·Stack/React

App.js

import './App.css';
import UserCustomHook from './components/UsersCustomHook';
// 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/> */}
      <UserCustomHook/>
    </div>
  );
}

export default App;

 

components/UsersCustomHook.js

// useAsync를 사용해서 비동기 전송을 받아와 사용
import React, { useState } from 'react';
import axios from 'axios';
import useAsync from './useAsync';
import User from './User';

async function getUsers() {
    const response = await axios.get('https://jsonplaceholder.typicode.com/users');
    return response.data;
}

const UserCustomHook = () => {
    const [userId, setUserId] = useState(null);
    const [state, refetch] = useAsync(getUsers, [], true);
    const { loading, data, error } = state;
    if(loading) return <div>로딩중...</div>
    if(error) return <div>에러가 발생했습니다.</div>
    if(!data) return <button onClick={refetch}>불러오기</button>
    return (
        <div>
             <ul>
                {data.map(user => (
                        <li key={user.id} onClick={()=>{
                            setUserId(user.id)
                        }}>
                            {user.username} ({user.name})
                        </li>
                    )    
                )}
            </ul>
            <button onClick={refetch}>다시 불러오기</button>
            {userId && <User id = {userId}/>}
        </div>
    );
};

export default UserCustomHook;

 

components/useAsync.js

import { useReducer, useEffect } from 'react';
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;
}
}
function useAsync(callback, deps = [], skip = false) {
    const [ state, dispatch ] = useReducer(reducer, initialState);
    const fetchDate = async () => {
        dispatch({ type: "LOADING" });
        try{
            const data = await callback();
            dispatch({
                type: "SUCCESS",
                data: data
            })
        }
        catch(e) {
            dispatch({
                type: "ERROR",
                error: e
            })
        }
    }
    useEffect(()=>{
        // skip이 true면 리턴 fetchDate() 실행안됨
        if(skip) return;
        fetchDate();
        // ↓ eslint 설정을 다음 줄에서만 비활성화
        // eslint-disable-next-line
    }, deps)
    return [state, fetchDate];
}
export default useAsync;

 

Components/User.js

import React from 'react';
import axios from 'axios';
import useAsync from './useAsync';

async function getUser(id) {
    const response = await axios.get(
        `https://jsonplaceholder.typicode.com/users/${id}`
    );
    return response.data;
}

const User = ({id}) => {
    const [ state ] = useAsync(()=> getUser(id), [id]);
    const { loading, data, error } = state;
    if(loading) return <div>로딩중...</div>
    if(error) return <div>에러가 발생했습니다.</div>
    if(!data) return null
    return (
        <div>
            <h2>{data.username}</h2>
            <p>
                Email: {data.email}
            </p>
        </div>
    );
};

export default User;

.

.

.

2022.06.28 - [Coding/React] - [React] API 연동하기

 

'Stack > React' 카테고리의 다른 글

[React] Lamp 쇼핑몰 구현하기 2 (Node.js 서버 만들기)  (0) 2022.06.30
[React] Lamp 쇼핑몰 구현하기 1  (0) 2022.06.29
[React] useState / useReducer / Context API 복습  (0) 2022.06.29
[React] API 연동하기  (0) 2022.06.28
[React] Router / 중첩 라우팅  (0) 2022.06.28
'Stack/React' 카테고리의 다른 글
  • [React] Lamp 쇼핑몰 구현하기 2 (Node.js 서버 만들기)
  • [React] Lamp 쇼핑몰 구현하기 1
  • [React] useState / useReducer / Context API 복습
  • [React] API 연동하기
7ingout
7ingout
  • 7ingout
    Hello, 7ingout world!
    7ingout
  • 전체
    오늘
    어제
    • 분류 전체보기 (205)
      • Project (5)
      • Stack (173)
        • React (40)
        • JavaScript (50)
        • TypeScript (14)
        • HTML (11)
        • CSS (31)
        • Spring (9)
        • PHP (15)
        • SQL (3)
        • Python (0)
      • ETC (9)
      • Design (13)
        • Illustrator (6)
        • Photoshop (7)
      • Articloid (4)
        • 7ingout (4)
  • 공지사항

    • ☻
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
7ingout
[React] API 연동하기 2
상단으로

티스토리툴바