IT/React

[React] 자바스크립트, 리액트 비동기 통신

HJ:: 2023. 9. 15. 21:02

Async/await , fetch()

전역 fetch() 메서드는 네트워크에서 리소스를 취득하는 절차를 시작하고, 응답이 사용 가능해지면 이행하는 프로미스를 반환합니다.

 

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

const Async = () => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isError, setIsError] = useState(false);

  async function getDataByAsync() {
    try {
      const response = await fetch("https://rickandmortyapi.com/api/character");
      const data = await response.json();
      setData(data.results);
      setIsLoading(false);
    } catch (error) {
      setIsError(true);
      setIsLoading(false);
    }
  }

  useEffect(() => {
    getDataByAsync();
  }, []); // useEffect를 사용하여 컴포넌트가 마운트될 때 데이터를 가져옵니다.

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error loading data</div>;

  return (
    <div>
      <Link to={"-1"}>back</Link>
      <h1>Rick and Morty Characters</h1>
      <ul>
        {data.map((character) => (
          <li key={character.id}>{character.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default Async;

이 코드에서는 React의 useState와 useEffect 훅을 사용하여 데이터 가져오기와 UI 렌더링을 관리하고, try-catch를 사용하여 오류 처리를 수행합니다. 이렇게 하면 데이터를 가져올 때의 비동기 문제를 처리하고, UI를 업데이트하거나 오류 메시지를 표시할 수 있게 됩니다.

 

await 키워드는 async 함수에서만 유효하다

async 함수는 항상 promise를 반환합니다. 

 

 

 

 

AJAX

AJAX (Asynchronous Javascript And XML)

 

//fetch
  const url = "https://rickandmortyapi.com/api/character";
  const options = {
    method: "GET",
    header: {
      Accept: "application/json",
      "Content-Type": "application/json",
      charset: "UTP-8",
    },
  };

  fetch(url, options)
    .then((response) => response.json())
    .then((data) => {
      console.log(data.results);
    })
    .catch((error) => {
      console.error("데이터 가져오기 실패:", error);
    });

 

 

 //axios
  const getData = async () => {
    const response = await axios.get(
      "https://rickandmortyapi.com/api/character"
    );
    return response.data.results;
  };
  const { data, isLoading, isError } = useQuery("characters", getData);
  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error loading data</div>;

  console.log(data)

 

Ajax

AJAX는 비동기식 자바스크립트와 XML(Asynchronous JavaScript And XML)의 약자로, 브라우저가 페이지 전체를 새로 고치지 않고도 서버로부터 데이터를 비동기적으로 로드하고 화면을 업데이트하는 기술입니다. 이를 구현하기 위해 JavaScript를 사용하여 서버와 비동기 통신하며, 주로 XML 데이터를 주고받는 기술로 시작했지만 현재는 JSON을 더 많이 사용합니다.

 

 

  1. Fetch API: Fetch API는 최신 웹 표준으로, 브라우저에서 제공하는 내장 함수로서 간단하고 강력한 HTTP 요청을 만들 수 있습니다. 주로 Promise를 기반으로 하며, 다음과 같이 사용할 수 있습니다.
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // 데이터 처리 로직
  })
  .catch(error => {
    // 오류 처리 로직
  });

 

 

  1. axios 라이브러리: axios는 브라우저와 Node.js에서 모두 사용 가능한 HTTP 클라이언트 라이브러리로, 더 다양한 기능과 브라우저 호환성을 제공합니다. axios는 Promise 기반으로 작동하며 사용하기 쉽고, 오류 처리 및 요청 취소와 같은 고급 기능을 제공합니다.
import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => {
    // 데이터 처리 로직
  })
  .catch(error => {
    // 오류 처리 로직
  });

 

 

  1. POST 요청
    • POST 요청은 데이터를 서버로 보내는 데 사용됩니다.
    • Post를 사용하면 주소창에 쿼리스트링이 남지 않기때문에 GET보다 안전하다.
import axios from 'axios';

const newData = { name: '새로운 데이터', value: 42 };

axios.post('https://api.example.com/data', newData)
  .then(response => {
    console.log('데이터 전송 성공:', response.data);
  })
  .catch(error => {
    console.error('데이터 전송 실패:', error);
  });

 

 

  1. PUT 요청
    • PUT 요청은 서버의 데이터를 업데이트하는 데 사용됩니다.
import axios from 'axios';

const updatedData = { id: 1, name: '수정된 데이터', value: 55 };

axios.put('https://api.example.com/data/1', updatedData)
  .then(response => {
    console.log('데이터 업데이트 성공:', response.data);
  })
  .catch(error => {
    console.error('데이터 업데이트 실패:', error);
  });
  1. DELETE 요청
    • DELETE 요청은 서버의 데이터를 삭제하는 데 사용됩니다.
import axios from 'axios';

axios.delete('https://api.example.com/data/1')
  .then(response => {
    console.log('데이터 삭제 성공:', response.data);
  })
  .catch(error => {
    console.error('데이터 삭제 실패:', error);
  });

 

 

- React Query 사용하면 데이터 관리와 통신을 쉽게 처리할 수 있도록 도와주는 강력한 라이브러리로, 다음과 같은 장점을 제공합니다:

const { data, error, isLoading } = useQuery('todos', async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos');
    if (!response.ok) {
      throw new Error('데이터를 불러오지 못했습니다.');
    }
    return response.json();