[React] Promise & .get().then().catch() 비동기 작업

hellow_coding·2023년 10월 9일

.get, .then, .catch는 JavaScript에서 프로미스(Promise)를 사용하여 비동기 작업을 다룰 때 사용되는 구조입니다. 비동기 작업은 일반적으로 네트워크 요청, 파일 읽기/쓰기, 데이터베이스 쿼리 등과 같이 시간이 오래 걸리거나 외부 리소스에 접근해야 하는 작업을 말합니다.

1. .get 메서드

axios.get(url)
  • 서버로부터 데이터를 가져오는데 사용됩니다.
  • 주어진 URL로 GET 요청을 보내고, 서버에서 응답을 대기합니다.

2. .then 메서드

axios.get(url)
  .then(response => {
    // 성공 시 실행할 코드
  })
  • 프로미스 객체의 메서드로, 비동기 작업이 성공했을 때 실행할 콜백 함수를 등록하는데 사용됩니다.
  • 비동기 작업이 완료되면 해당 작업의 결과값을 인자로 받아 실행합니다.
  • 성공적인 작업 이후에 실행할 로직을 정의할 수 있습니다.

3. .catch 메서드

axios.get(url)
  .then(response => {
    // 성공 시 실행할 코드
    console.log('데이터를 성공적으로 받다았습니다:', response.data);
  })
  .catch(error => {
    // 에러 시 실행할 코드
    console.error('요청 중 에러 발생:', error);
  })
  • 프로미스 객체의 메서드로, 비동기 작업에서 에러가 발생했을 때 실행할 콜백 함수를 등록하는데 사용됩니다.
  • 에러 처리 로직을 정의할 수 있습니다.
  • .then 체인 내에서 에러가 발생하면 .catch 블록으로 이동하여 에러를 처리합니다.



※ 토큰을 사용하여 인증하고 GET 및 POST 요청을 보내는 예제 코드

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

function App() {
  const [data, setData] = useState([]);
  const [token, setToken] = useState(''); // 토큰 상태

  useEffect(() => {
    // 서버에서 토큰을 발급하거나 저장된 토큰을 가져와서 설정합니다.
    // 로그인 또는 인증 후에 토큰을 설정하는 부분입니다.
    const userToken = 'your_jwt_token_here';
    setToken(userToken);

    // GET
    axios.get('https://api.example.com/data', {
      headers: {
        'Authorization': `Bearer ${token}` // JWT 토큰을 헤더에 포함 (토큰 인증)
      }
    })
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('GET 요청 에러:', error);
      });

    // POST
    const postData = {
      username: 'example_user',
      password: 'example_password'
    };

    axios.post('https://api.example.com/login', postData, {
      headers: {
        'Authorization': `Bearer ${token}` // JWT 토큰을 헤더에 포함 (토큰 인증)
      }
    })
      .then(response => {
        console.log('로그인 결과:', response.data);
      })
      .catch(error => {
        console.error('POST 요청 에러:', error);
      });
  }, [token]);

  return (
    <div className="App">
      <h1>인증 및 API 요청 예제</h1>
      <ul>
        {data.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
profile
꿈많은 개발자

0개의 댓글