본문 바로가기
타입스크립트로 함께하는 웹 풀 사이클 개발(React, Node.js)/TIL

api 요청 플로우 , params 처리

by 슈크림 붕어빵 2024. 3. 1.

 

View => 화면에 데이터 사용 
Hooks => api마다 가공 및 useEffect등 설정
Fecher => api 통신

 

요약해보면 위와 같다.

 

다음으로 api 로직 예시와 여러가지 params를 붙여 api 통신을 하는 경우를 살펴보겠다.

 

api 로직 예시

 

axios를 이용해서 api를 요청해보겠다.

npm i axios --save

 

 

component/ common/ header.tsx

const { category } = useCategory();​

=> hook과 연결하는 부분 , category 받아와서 화면에 사용

 

 

hooks/ useCategory.ts

import { useEffect, useState } from "react";
import { fetchCategory } from "../api/category.api";
import { Category } from "../models/category.model";

export const useCategory = () => {
  const [category, setCategory] = useState<Category[]>([]);

  useEffect(() => {
    fetchCategory().then((category) => {
      if (!category) return; //카테고리가 없는 경우?
      const categoryWithAll = [
        {
          category_id: null,
          category_name: "전체",
        },
        ...category,
      ];
      setCategory(categoryWithAll);
    });
  }, []);
  return { category };
};​

 

=> useEffect를 사용하여 화면이 리로드될 때마다 새로 받아오도록 구현, 가공하여 전체를 추가하여 category 반환

 

 

api/ category.api.ts

import { httpClient } from "./http";

export const fetchCategory = async () => {
  const response = await httpClient.get("/categories");

  return response.data;
};

=> api 통신하여 response를 받아옴

 

api/ https.ts

import axios, { AxiosRequestConfig } from "axios";

const BASE_URL = "http://localhost:8080";
const DEFAULT_TIMEOUT = 30000;

export const createClient = (config?: AxiosRequestConfig) => {
  const axiosInstance = axios.create({
    baseURL: BASE_URL,
    timeout: DEFAULT_TIMEOUT,
    headers: {
      "Content-Type": "application/json",
    },
    withCredentials: true,
    ...config,
  });
  axiosInstance.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  return axiosInstance;
};

export const httpClient = createClient();

=> Axios 인스턴스를 만들고 Axios 인스턴스에 응답 인터셉터를 추가

=> 이 경우에는 성공적인 요청에 대한 응답을 반환하고, 실패한 요청에 대해서는 프로미스를 거부

 

 

params를 붙여 api 통신하는 경우

import { httpClient } from "./http";
import { Book } from "../models/book.model";
import { Pagination } from "../models/pagination.model";
interface fetchBooksParams {
  category_id?: number;
  new?: boolean;
  currentPage?: number;
  limit: number;
}

interface FetchBooksResponse {
  books: Book[];
  pagination: Pagination;
}

export const fetchBooks = async (params: fetchBooksParams) => {
  const response = await httpClient.get<FetchBooksResponse>("/books", {
    params: params,
  });
  return response.data;
};