pending상태 중에 화면 잠금 방법, 및 pending상태 감지

wool·2023년 10월 17일
0

React

목록 보기
3/3

상태 관리 방법


가장 기본적인 접근방법

  1. 상태 관리

    먼저, 요청의 상태를 관리할 상태 변수가 필요합니다.

    const [isLoading, setIsLoading] = useState(false);
    
  2. API 요청

    API 요청을 시작할 때 setIsLoading(true)를 호출하고, 요청이 완료되면 setIsLoading(false)를 호출하여 상태를 업데이트합니다.

    const fetchData = async () => {
      setIsLoading(true);
      try {
        // API 요청
        await fetch('YOUR_API_ENDPOINT');
      } catch (error) {
        console.error('Error fetching data:', error);
      }
      setIsLoading(false);
    };
    
  3. 로딩 인디케이터 컴포넌트

    로딩 인디케이터를 전체 화면 오버레이로 표시하는 컴포넌트를 생성합니다.

    import styled from 'styled-components';
    
    const Overlay = styled.div`
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 999;
    `;
    
    function LoadingIndicator() {
      if (!isLoading) return null;
    
      return (
        <Overlay>
          {/* 여기에 로딩 인디케이터를 추가. 예: <Spinner /> */}
        </Overlay>
      );
    }
    
  4. 컴포넌트 렌더링

    메인 컴포넌트 내에서 LoadingIndicator 컴포넌트를 렌더링합니다.

    function YourComponent() {
      return (
        <div>
          {/* ... 다른 컴포넌트들 */}
          <LoadingIndicator />
        </div>
      );
    }
    

이렇게 하면, API 요청이 pending 상태일 때만 로딩 인디케이터가 전체 화면에 오버레이로 표시됩니다.

상태 관리 이외의 방법


  1. Fetch API와 AbortController 사용:
    AbortController를 사용하면 fetch API의 요청을 취소할 수 있습니다. 이를 활용해 요청이 아직 진행 중인지(pending) 여부를 감지할 수 있습니다.
    ```jsx
    const controller = new AbortController();
    const { signal } = controller;
    
    fetch('YOUR_API_ENDPOINT', { signal })
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .catch(error => {
        if (error.name === 'AbortError') {
          console.log('Fetch aborted');
        } else {
          console.error('Fetch error:', error.message);
        }
      });
    
    ```
  2. XMLHttpRequest 객체의 readyState 속성 사용:
    XMLHttpRequest 객체는 readyState 속성을 통해 요청의 상태를 제공합니다. readyState가 1(OPENED) 또는 2(HEADERS_RECEIVED) 상태라면 요청이 pending 상태인 것으로 간주할 수 있습니다.
    ```jsx
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState === XMLHttpRequest.OPENED || xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
        console.log('Request is pending');
      }
    };
    xhr.open('GET', 'YOUR_API_ENDPOINT', true);
    xhr.send();
    
    ```
  3. axios 라이브러리의 interceptors 활용:
    axios를 사용하는 경우, interceptors를 사용해 요청과 응답을 가로채서 처리할 수 있습니다. 이를 활용하면 요청이 시작되었을 때와 종료되었을 때를 감지할 수 있습니다.
    ```jsx
    import axios from 'axios';
    
    axios.interceptors.request.use(
      config => {
        console.log('Request started'); // 요청 시작
        return config;
      },
      error => Promise.reject(error)
    );
    
    axios.interceptors.response.use(
      response => {
        console.log('Request finished'); // 요청 종료
        return response;
      },
      error => Promise.reject(error)
    );
    
    ```

위의 방법들 중 하나를 선택하여 pending 상태를 감지할 수 있습니다. 사용하는 기술 스택 및 요구 사항에 따라 적절한 방법을 선택하는 것이 좋습니다.

profile
毎日一つづつゆっくり

0개의 댓글