[프로젝트]물건 공유 플랫폼- 2 (구현)

else·2023년 6월 28일
0

프로젝트

목록 보기
10/12

ErrorBoundary

  • ErrorBoundary란?

    • 컴포넌트에서 Error 가 발생했을 때 이를 감지해서 사용자에게 미리 구현해놓은 에러 컴포넌트로 리다이렉트 시켜주는 React v16 이상에서 내장되어있는 컴포넌트이다.
    • 나는 이것을 axios 요청하는 컴포넌트들에 대해 미리 설정을 해 로드 중 에러가 난다면 다시 axios요청을 보낼 수 있는 버튼을 생성해 사용자의 흐름이 끊기지 않도록 했다.
  • Docs

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // 다음 렌더링에서 폴백 UI가 보이도록 상태를 업데이트 합니다.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 에러 리포팅 서비스에 에러를 기록할 수도 있습니다.
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 폴백 UI를 커스텀하여 렌더링할 수 있습니다.
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

다음과 같이 클래스 형태의 컴포넌트를 선언해 사용할 수 있다.

  • 사용 예시
/// 에러 컴포넌트 ///
import React, { ErrorInfo, ReactNode } from "react";

interface Props {
  children?: ReactNode;
  fallback: React.ElementType;
}

interface State {
  hasError: boolean;
  error: Error | null;
}
const initialState: State = {
  hasError: false,
  error: null,
};

class ErrorBoundary extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = initialState;
  }

  public static getDerivedStateFromError(error: Error): State {
    // 다음 렌더링에서 폴백 UI가 보이도록 상태를 업데이트 합니다.
    return { hasError: true, error };
  }

  public render() {
    const { hasError, error } = this.state;

    if (hasError) {
      return <this.props.fallback error={error} />;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
/// fallback UI ///
const ErrorMsg = (error: any) => {
  const { reset } = useQueryErrorResetBoundary();

  const queryClient = useQueryClient();
  const refetch = () => {
    return queryClient.refetchQueries(["get-object-list"]);
  };

  const reTry = () => {
    reset();
    refetch();
  };
  return (
    <div>
      <p>잠시 후 다시 시도해주세요</p>
      <p>요청을 처리하는데</p>
      <p>실패했습니다.</p>
      <button onClick={reTry}>다시시도</button>
    </div>
  );
};
<ErrorBoundary fallback={ErrorMsg}>
   <Suspense fallback={<Loading />}>
       <UserHomeList />
   </Suspense>
</ErrorBoundary>
profile
피아노 -> 개발자

0개의 댓글