3. Next.js용 공통 유틸 RestApi 사용

이 문서는 Next.js용 RestApi를 사용하여 데이터를 가져오는 방법에 대한 안내입니다.

Next.js에서는 Server component, Client component에 따라 restApiUtil의 사용법이 조금씩 달라집니다. 또한 Next.js 내에서 반복적으로 수행하는 공통 기능 등을 추가한 next(react)에 맞춰서 만들어진 RestApi Util을 제공합니다.

  • 둘다 사이트(비즈니스 로직)에 맞춰서 공통화된 기능이 들어가 있음. (쿠키값에서 token을 가져와 추가 등)

  • Server component의 내부적으로 Server Action 기능을 사용함

  • Client component의 경우 내부적으로 React Hook 기능을 사용함

1

Server Component

Server Component는 Promise를 반환하므로 then/catch 패턴이나 async/await 문법을 사용하여 처리합니다. 아래 예시는 async/await를 사용한 예입니다.

app/page.tsx (Server Component 예시)
import { restApi } from '@/lib/common/plugins/restApi';

const Home = async () => {
  const response = await restApi.get('/api/display/v1/shop/1?dispMediaCd=20');
  console.log(response);

  return (
    <div>
      <h1>Home</h1>
    </div>
  );
};

export default Home;

Server Component에서는 내부적으로 Server Action 기능을 사용하도록 구현되어 있습니다.

2

Client Component

Client Component에서는 React Hook을 사용하여 데이터를 가져옵니다. useEffect 내부나 이벤트 핸들러에서 async 함수를 호출하는 방식이 일반적입니다.

app/page.tsx (Client Component 예시)
'use client';
import { useEffect } from 'react';
import { restApi } from '@/lib/common/plugins/restApi';

const Home = () => {
  useEffect(() => {
    const apiFunc = async () => {
      const response = await restApi.get('/api/display/v1/shop/1?dispMediaCd=20');
      console.log(response);
    };
    apiFunc();
  }, []);

  async function apitest() {
    const response = await restApi.get('/api/display/v1/shop/1?dispMediaCd=20');
    console.log(response);
  }

  return (
    <div>
      <h1>Home</h1>
      <button onClick={() => apitest()}>api test</button>
    </div>
  );
};

export default Home;

Client Component는 내부적으로 React Hook 기반 구현을 사용합니다.

3

x2bee 표준 및 관리를 위한 api 작성 방법

화면마다 개별적으로 API를 작성하기보다, 프로젝트 내에 api 디렉토리를 만들어 업무 또는 API별 파일로 분리해 작성하는 것을 권장합니다. 이렇게 하면 중복 코드를 줄이고 관련 API를 함께 관리하여 통일성을 유지하기 좋습니다.

예시:

src/api/categoryApi.ts
import { restApi } from '@/lib/common/plugins/restApi';
import { DisplayCategory } from '@/types/display/category-data-model';
import { ResponseEntity } from '@/lib/common/plugins/restApi/restApiModel';

const CategoryApi = async (params?: { brandNo: string }) => {
  const response: ResponseEntity = (await restApi.get(
    '/api/display/v1/displayCategory',
    { params }
  )) as ResponseEntity;

  return (response.payload || []) as DisplayCategory[];
};

export default CategoryApi;

마지막 업데이트