프로그램

React fetch 기능

다온다올과함께 2025. 1. 19. 07:00

 

 

 

React에서 fetch는 데이터를 가져오기 위해 사용되는 기본 JavaScript API입니다. 주로 REST API와 통신하거나 외부 데이터를 가져올 때 활용됩니다. fetch는 Promise 기반이므로 비동기 작업을 수행하는 데 적합하며 React의 상태 관리와 결합하여 유용하게 사용할 수 있습니다.

 


 

기본 사용법

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // JSON 데이터를 파싱
  })
  .then(data => {
    console.log(data); // 가져온 데이터
  })
  .catch(error => {
    console.error('Fetch error:', error); // 에러 처리
  });

 


 

React에서 fetch 활용하기

useEffect와 useState를 함께 사용하여 데이터를 가져오고 상태로 관리합니다.

 

1. 기본 데이터 가져오기

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

function DataFetcher() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => {
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        return response.json();
      })
      .then(data => {
        setData(data);
        setLoading(false);
      })
      .catch(error => {
        setError(error.message);
        setLoading(false);
      });
  }, []); // 빈 배열로 마운트 시 한 번만 실행

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <div>
      {data && data.map(item => <p key={item.id}>{item.name}</p>)}
    </div>
  );
}

export default DataFetcher;

 


 

2. 비동기 함수로 Fetch 분리

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

function DataFetcher() {
  const [data, setData] = useState(null);

  const fetchData = async () => {
    try {
      const response = await fetch('https://api.example.com/data');
      if (!response.ok) {
        throw new Error('Failed to fetch');
      }
      const result = await response.json();
      setData(result);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
      {data ? (
        data.map(item => <p key={item.id}>{item.name}</p>)
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default DataFetcher;

 


 

Fetch with POST Request

fetch는 데이터를 보내는 데도 사용할 수 있습니다. method, headers, body 옵션을 설정하여 POST 요청을 수행합니다.

const postData = async () => {
  try {
    const response = await fetch('https://api.example.com/data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: 'New Item',
        description: 'This is a new item',
      }),
    });

    if (!response.ok) {
      throw new Error('Failed to post data');
    }

    const result = await response.json();
    console.log('Posted data:', result);
  } catch (error) {
    console.error(error);
  }
};

postData();

 


 

에러 처리

  • fetch는 네트워크 에러만 잡아내므로, HTTP 상태 코드(예: 404, 500)는 추가로 처리해야 합니다.
  • 상태 코드 처리 예제
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .catch(error => {
    console.error('Error:', error.message);
  });

 


 

React Fetch Best Practices

 

1. 로딩 상태 관리: 데이터를 가져오는 동안 사용자에게 로딩 상태를 보여줍니다.

2. 에러 처리: 네트워크 오류와 HTTP 상태 코드를 적절히 처리합니다.

3. 메모리 누수 방지

  • 컴포넌트가 언마운트된 상태에서 상태 업데이트를 방지합니다.
useEffect(() => {
  let isMounted = true;
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => {
      if (isMounted) setData(data);
    });
  return () => {
    isMounted = false;
  };
}, []);

 

4. Reusable 함수 작성: API 호출 코드를 컴포넌트 외부로 분리하여 재사용성을 높입니다.

 


 

fetch는 React에서 데이터를 가져오기 위한 기본 도구로 간단하면서도 강력합니다. 더 효율적인 상태 관리를 원한다면 React Query와 같은 라이브러리를 사용하는 것도 좋은 선택입니다.

 

 

 

 

 

 

 

 

 

#프로그래밍배우기 #React #fetch #API

 

 

 

 

 

 

 

반응형