All files / src/chap08 WeatherLazyPage.js

0% Statements 0/23
0% Branches 0/11
0% Functions 0/5
0% Lines 0/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                                                                                                               
import { isRouteErrorResponse, json,
  useLoaderData, useRouteError } from 'react-router-dom';
 
const sleep = ms => new Promise(res => setTimeout(res, ms));
 
// 로더 함수 정의
export async function loader({ params }) {
  await sleep(2000);
  const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${params.city}&lang=kr&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`);
  if (res.ok) { return res; }
  switch (res.status) {
    case 404:
      throw json({ message: 'city is invalid!!' }, { status: 404 });
    case 401:
      throw json({ message: 'api key is invalid!!' }, { status: 401 });
    default:
      throw json({ message: 'unknown error...' }, { status: 503 });
  }
};
 
// 컴포넌트 함수 정의
export function Component() {
  const data =  useLoaderData();
  return (
    <figure>
      <img src={`https://openweathermap.org/img/wn/${data?.weather?.[0]?.icon}.png`}
      alt={data?.weather?.[0]?.main} />
      <figcaption>{data?.weather?.[0]?.description}</figcaption>
    </figure>
  );
}
Component.displayName = 'WeatherLazyPage';
 
// 오류 페이지 정의
export function ErrorBoundary() {
  const error = useRouteError();
  if (isRouteErrorResponse(error)) {
    switch (error.status) {
      case 404:
        return <p>원하는 페이지를 찾을 수 없습니다.</p>;
      case 401:
        return <p>인증에 실패했습니다.</p>;
      case 501:
        return <p>서비스가 일시적으로 중단되었습니다.</p>;
      default:
        return <p>알 수 없는 오류: {error.data.message}</p>;
    }
  }
  return (
    <div>
      <h3>문제가 발생했습니다.</h3>
      <p>상세한 문제: {error.message}</p>
    </div>
  );
}
ErrorBoundary.displayName = 'WeatherLazyErrorPage';