본문 바로가기
프런트엔드/리엑트

📡 Axios를 활용한 React API 데이터 연동

by Alan__kang__morlang 2025. 4. 2.
반응형

이번 글에서는 Axios를 이용하여 React에서 API 데이터를 가져오는 방법과 실무에서 자주 쓰이는 로딩 처리 및 에러 처리 방법까지 다뤄보겠습니다.

✅ Axios란?

Axios는 HTTP 요청을 쉽게 만들 수 있는 JavaScript 라이브러리로, 간편하고 강력한 기능을 제공하여 많은 React 개발자들이 선호합니다.

🚩 Axios 설치 방법

npm install axios

📌 Axios로 API 요청하기


axios.get('https://api.example.com/data')
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error('API 요청 중 에러 발생:', error);
    });
    

🚀 React에서 API 데이터 연동 실무 예제


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

    useEffect(() => {
        axios.get('https://api.example.com/data')
            .then(response => {
                setData(response.data);
                setLoading(false);
            })
            .catch(error => {
                setError(error.message);
                setLoading(false);
            });
    }, []);

    if (loading) return <div>로딩 중...</div>;
    if (error) return <div>에러 발생: {error}</div>;

    return (
        <ul>
            {data.map(item => (
                <li key={item.id}>{item.name}</li>
            ))}
        </ul>
    );
}

🔖 실무에서의 Axios 사용 팁

  • 공통 API 설정 관리: Axios 인스턴스를 생성하여 기본 URL 및 헤더를 전역에서 관리하면 편리합니다.
  • 로딩 상태 관리: 요청이 진행되는 동안 로딩 상태를 사용자에게 명확하게 전달하는 것이 좋습니다.
  • 에러 처리: API 에러를 명확히 처리하여 사용자 경험을 개선하고 유지보수성을 높입니다.

🎈 마무리

이 글에서 소개한 내용을 참고하여 Axios를 React에 효과적으로 적용하고, API 연동을 더욱 쉽고 안정적으로 구현해 보세요!

 

반응형