api 결과값의 타입에 자꾸 undefined가 포함된다면

Sheryl Yun·2023년 5월 3일
0

api 폴더의 fetchResults 호출 함수를 다른 곳에서 사용할 때 결과값에 계속 undefined가 포함되는 문제가 있었다.

undefined나 null 없이 깔끔한 타입으로 값을 내보내고 싶었다.
고민해보니 try 안에 분기(if문)가 있거나 catch문으로 넘어갈 때 반환되는 값이 없으면 undefined 타입이 추가되는 것 같았다.

그래서 다음과 같이 try 안의 if문을 지우고(원래는 status code가 200인지 확인함) catch문 안의 console.log 밑에 에러를 자체 처리하는 throw new Error 문구를 추가했다.

import axios from 'axios';
import { ResultState } from 'types/searchResult';

interface SearchResultType {
  data: Promise<ResultState[]>;
}

const fetchResults = async (keyword: string) => {
  try {
    const { data: searchResultData }: SearchResultType = await axios.get(
      `/api/v1/search-conditions/?name=${keyword}`,
      {
        withCredentials: true,
      }
    );

    console.info('calling api');

    return searchResultData;
  } catch (err) {
    console.log(err);
    throw new Error('api 호출이 실패하였습니다.'); // undefined 에러를 지우기 위해 추가한 부분
  }
};

export const searchAPI = {
  fetchResults,
};

결과적으로 함수의 결과값으로 반환되는 searchResultData에 null이나 undefined 같은 타입이 포함이 안 되어 다른 데서(예: redux) 편하게 사용할 수 있었다.

profile
데이터 분석가 준비 중입니다 (티스토리에 기록: https://cherylog.tistory.com/)

0개의 댓글