React 데이터 통신

정현승·2024년 12월 4일

데이터 통신

리액트에서 데이터 통신을 할 때는 axios 라이브러리나 fetch API를 사용하여 처리합니다.
여러가지 편의 기능은 axios 라이브러리가 더 뛰어나지만, 별도의 라이브러리를 설치해서 사용해야 한다는 단점이 있습니다.

Fetch API GET

Fetch API는 브라우저 내장 HTTP 요청 라이브러리로, 최신 웹 표준입니다.

import { useEffect, useState } from 'react';

export default function Fetch1() {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    fetch('http://localhost:3001/posts')
      .then((res) => {
        if (!res.ok) {
          throw Error('Could not fetch the data for that resource');
        }
        return res.json();
      })
      .then((data) => {
        setPosts(data);
      });
  }, []);
  return <pre>{JSON.stringify(posts, null, 2)}</pre>;
}

Fetch API Post, Put, Patch, Delete

export default function FetchCURD() {
  
  const postHandler = async () => {
    try {
      const res = await fetch('http://localhost:3001/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: '3', title: 'a title', views: 100 }),
      });

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

      const data = await res.json();
      console.log(data);
    } catch (e) {
      console.log(e);
    }
  };

  
  const deleteHandler = async () => {
    try {
      const res = await fetch('http://localhost:3001/posts/3', {
        method: 'DELETE',
      });

      if (!res.ok) {
        throw new Error('Failed to delete');
      }

      const data = await res.json();
      console.log(data);
    } catch (e) {
      console.log(e);
    }
  };

  
  const putHandler = async () => {
    try {
      const res = await fetch('http://localhost:3001/posts/1', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ title: 'a new title', views: 200 }),
      });

      if (!res.ok) {
        throw new Error('Failed to put');
      }

      const data = await res.json();
      console.log(data);
    } catch (e) {
      console.log(e);
    }
  };

  
  const patchHandler = async () => {
    try {
      const res = await fetch('http://localhost:3001/posts/1', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ title: 'a patch title' }),
      });

      if (!res.ok) {
        throw new Error('Failed to patch');
      }

      const data = await res.json();
      console.log(data);
    } catch (e) {
      console.log(e);
    }
  };
  return (
    <>
      <button onClick={postHandler}>POST</button>
      <button onClick={deleteHandler}>DELETE</button>
      <button onClick={putHandler}>PUT</button>
      <button onClick={patchHandler}>PATCH</button>
    </>
  );
}

Axios

Axios는 HTTP 요청을 처리하기 위한 서드파티 라이브러리입니다.
요청과 응답 데이터를 자동 변환합니다.

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

export default function Axios1() {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    axios
      .get('http://localhost:3001/posts')
      .then(({ status, statusText, data }) => {
        console.log(status, statusText, data);
        setPosts(data);
      });
  }, []);

  return <pre>{JSON.stringify(posts, null, 2)}</pre>;
}

Axios Post, Put, Patch, Delete

import axios from 'axios';

export default function AxiosCRUD() {
  const postHandler = async () => {
    try {
      const res = await axios.post('http://localhost:3001/posts', {
        id: '3',
        title: 'a title',
        views: 100,
      });

      console.log(res.data);
    } catch (e) {
      console.log(e);
    }
  };

  const deleteHandler = async () => {
    try {
      const res = await axios.delete('http://localhost:3001/posts/3');
      console.log(res.data);
    } catch (e) {
      console.log(e);
    }
  };

  const putHandler = async () => {
    try {
      const res = await axios.put('http://localhost:3001/posts/1', {
        title: 'a new title',
        views: 500,
      });

      console.log(res.data);
    } catch (e) {
      console.log(e);
    }
  };

  const patchHandler = async () => {
    try {
      const res = await axios.patch('http://localhost:3001/posts/1', {
        title: 'a patch title',
      });

      console.log(res.data);
    } catch (e) {
      console.log(e);
    }
  };

  return (
    <>
      <button onClick={postHandler}>POST</button>
      <button onClick={deleteHandler}>DELETE</button>
      <button onClick={putHandler}>PUT</button>
      <button onClick={patchHandler}>PATCH</button>
    </>
  );
}

axios.create

axios.create() 메서드를 사용하여 기본 구성 옵션을 설정하고 재사용 가능한 Axios 인스턴스를 만드는 방법입니다.
이를 사용하면 여러 컴포넌트나 파일에서 HTTP 요청을 효율적으로 관리할 수 있습니다.

import axios from "axios";

export const axiosInstance = axios.create({
  baseURL: `https://api.themoviedb.org/3/movie`,
  headers: {
    Authorization:
      "Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI3Nzk1Y2EwNDE0MTE0NzM3MGNmZmFkZjFjOTc2ZWRkNCIsIm5iZiI6MTczMzI5MTIzOS44Miwic3ViIjoiNjc0ZmVjZTc0NDg0N2U5N2RmZjQwM2YwIiwic2NvcGVzIjpbImFwaV9yZWFkIl0sInZlcnNpb24iOjF9.DjLrcmHH_hv2Y9c_Qj_N3lqwNNLcxsv5yThiGFgkARQ",
  },
});

export const getNowPlaying = async () => {
  try {
    const { data } = await axiosInstance.get(
      `/now_playing?language=en-US&page=1`
    );
    return data;
  } catch (error) {
    throw new Error("API 호출을 실패했습니다.");
  }
};

export const getUpcoming = async () => {
  try {
    const { data } = await axiosInstance.get(
      `/upcoming?language=en-US&page=1`
    );
    return data;
  } catch (error) {
    throw new Error("API 호출을 실패했습니다.");
  }
};

export const getTopRated = async () => {
  try {
    const { data } = await axiosInstance.get(
      `/top_rated?language=en-US&page=1`
    );
    return data;
  } catch (error) {
    throw new Error("API 호출을 실패했습니다.");
  }
};

0개의 댓글