노력이 좋아서

<step69>'react_axios'

zoaseo 2022. 6. 28. 14:17

1) 

App.js

import './App.css';
import Users from './components/Users';
import UsersReducer from './components/UsersReducer';
import Posts from './components/Posts';
import PostsReducer from './components/PostsReducer';
function App() {
  return (
    <div className="App">
      {/* <Users/> */}
      <UsersReducer/>
      {/* <Posts/> */}
      <PostsReducer/>
    </div>
  );
}

export default App;

Users.js

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

const Users = () => {
    // 상태관리
    // 1. 요청의 결과
    // 2. 로딩상태
    // 3. 에러
    const [ users, setUsers ] = useState(null);
    const [ loading, setLoading ] = useState(false);
    const [ error, setError ] = useState(null);
    const fetchUsers = async () => {
        try {
            // 요청이 시작할 때에는 error와 users를 초기화
            setError(null);
            setUsers(null);
            // loading상태를 true로 변경
            setLoading(true);
            // 요청한 데이터는 response.data안에 있습니다.
            const response = await axios.get('https://jsonplaceholder.typicode.com/users');
            setUsers(response.data);
        }
        catch(e){
            setError(e);
        }
        setLoading(false);
    }
    useEffect(()=>{
        fetchUsers();
    },[])
    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>
            <button onClick={fetchUsers}>다시 불러오기</button>
        </div>
    );
};

export default Users;

UsersReducer.js

import React,{ useReducer, useEffect } from 'react';
import axios from 'axios';
// 초기값, reducer함수 생성
// loading, data, error
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;
    }
}
const UsersReducer = () => {
    const [ state, dispatch ] = useReducer(reducer, initialState);
    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, error } = state;
    if(loading) return <div>로딩중....</div>
    if(error) return <div>에러가 발생했습니다.</div>
    if(!data) return null
    return (
        <div>
              <ul>
                {data.map(user=>(
                    <li key={user.id}>
                        {user.username} ({user.name})
                    </li>
                )    
                )}
            </ul>
            <button onClick={fetchUsers}>다시 불러오기</button>
        </div>
    );
};

export default UsersReducer;

 

Posts.js

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

const Posts = () => {
    const [ posts, setPosts ] = useState(null);
    const [ loading, setLoading ] = useState(false);
    const [ error, setError ] = useState(null);
    const fetchPosts = async () => {
        try {
            setError(null);
            setLoading(true);
            setPosts(null);
            const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
            setPosts(response.data);
        }
        catch (e) {
            setError(e);
        }
        setLoading(false);
    }
    useEffect(()=>{
        fetchPosts();
    },[])
    if(loading) return <div>로딩중....</div>
    if(error) return <div>에러가 발생했습니다.</div>
    if(!posts) return null;
    return (
        <div>
            <table>
                <tr>
                    <th>id</th>
                    <th>title</th>
                    <th>body</th>
                </tr>
                {posts.map((post)=>
                    <tr key={post.userId}>
                        <td>{post.id}</td>
                        <td>{post.title}</td>
                        <td>{post.body}</td>
                    </tr>
                )}
            </table>
        </div>
    );
};

export default Posts;

PostsReducer.js

import React, { useEffect, useReducer } from 'react';
import axios from 'axios';
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;
    }
}
const PostsReducer = () => {
    const [ state, dispatch ] = useReducer(reducer,initialState);
    const fetchPosts = async () => {
        dispatch({type: 'LOADING'});
        try {
            const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
            dispatch({type: 'SUCCESS', data: response.data});
        }
        catch (e) {
            dispatch({type: 'ERROR', error: e});
        }
    }
    useEffect(()=>{
        fetchPosts();
    },[]);
    const { loading, data, error } = state;
    if(loading) return <div>로딩중입니다....</div>
    if(error) return <div>에러가 발생했습니다.</div>
    if(!data) return null
    return (
        <div>
            <table>
                <tr>
                    <th>id</th>
                    <th>title</th>
                    <th>body</th>
                </tr>
                {data.map(post=>(
                    <tr key={post.userId}>
                        <td>{post.id}</td>
                        <td>{post.title}</td>
                        <td>{post.body}</td>
                    </tr>
                ))}
            </table>
        </div>
    );
};

export default PostsReducer;
댓글수0