단순 코드 기록/React

React_Error 처리

일일일코_장민기 2024. 3. 19. 16:04
728x90
http
export async function fetchUserList(){

    //데이터 요청 응답 수신
    const response = await fetch("https://reqres.in/api/users?page=2", {
        //method: "GET"     //정상요청
        method: "PUT"   //에러 출력을 위한 put 사용
    });

    //비동기 요청: promise 객체 리턴 => await 처리
    //await 사용함수는 전체를 async 처리해주어야 함

    if(!response.ok){
        console.log("fetchUserList.Error");
        throw new Error("UsersList 요청 예외");
    }

    const resData = await response.json();

    return resData.data;
}

 

error

//에러가 출력될 때 나오는 방식
export default function Error({title, message}){
    return (
        <>
            <div>
                <h2>{title}</h2>
                <p>{message}</p>
            </div>
        </>
    )
}

 

App
import { useEffect, useState } from "react";
import { fetchUserList } from "./http";
import UsersList from "./components/UsersList"
import Error from "./components/Error";

export default function App(){

  const [usersList, setUsersList] = useState([]);
  const [isFetching, setIsFetching] = useState(false);
  const [error, setError] = useState();

  useEffect(() => {
    async function xxx(){
      setIsFetching(true);                         //가져오는 중

      //비동기함수의 구현
      try {
        const usersList = await fetchUserList();
        setUsersList(usersList);
      } catch (error) {                           //가져오는 도중 에러 발생 시
        console.log("Error: ", error.message);
        setError({messsage: error.message});      //에러에 메세지 저장
      }
      setIsFetching(false);                       //가져오기 완료
    }
    xxx();
  }, []);
  console.log("App 호출");

  return (
    <>
      <h1>User 목록</h1>
      {/* 에러가 발생할 경우: 에러 제목과 에러 메세지 전송 */}
      {error && (  <Error title="User목록: 예외발생됨" messsage={error.message}></Error>
      )}

      {/* 에러가 발생하지 않을 경우: 로딩중 여부, 유저 데이터, 로딩중 메세지, 유저 없음 메세지 전송 */}
      {!error &&(  <UsersList
          isLoading={isFetching}
          users = {usersList}
          loadingText="Fetching your users..."
          fallbackText="No users available"></UsersList>
      )}

    </>
  )

}

 

UsersList

 

export default function UsersList({ users, isLoading, loadingText, fallbackText }) {

    return (
      <>
        {/* 로딩 중일 때:  loadingText가 붉은 색으로 출력*/}
        {isLoading && <p style={{color: "red"}}>{loadingText}</p>}  
        {/* 로딩 중이 아닐 때: 유저가 없을 때는 fallbackText이 파랑 색으로 출력 */}                                                                    
        {!isLoading && users.length === 0 && (<p style={{color: "blue"}}>{fallbackText}</p>)}
        {/* 로딩 중이 아닐 때: 유저가 있을 때는 table 형태로 유저 데이터 출력 */}
        {!isLoading && users.length > 0 && (
            <table border={1}>
            <thead>
                <tr>
                    <td>아이디</td>
                    <td>이름</td>
                    <td>사진</td>
                </tr>
            </thead>
            <tbody>
                {users.map((user, idx) => {
                    return (
                        <tr key={idx}>
                            <td>{user.id}</td>
                            <td>{user.first_name}</td>
                            <td><img src={user.avatar} width="50" height= "50"></img></td>
                        </tr>
                    )
                })}
            </tbody>
          </table>
        )}
      </>
    );
  }

 

'단순 코드 기록 > React' 카테고리의 다른 글

React_외부데이터 + 데이터 추가  (0) 2024.03.20
React_외부데이터+modal  (0) 2024.03.20
React_https  (0) 2024.03.19
React_useMemo(고정값)  (0) 2024.03.19
React_memo  (0) 2024.03.19