[TIL #45 기업 협업] 리스트 검색 기능 (axios)

Whoyoung90·2021년 4월 22일
1
post-thumbnail

210423 WECODE #45 기업협업 10일차

> Today Mission

선사리스트 검색기능 추가

> 해결

filter함수에 includes( ) , toLowerCase( ) 사용

cf. fetch 함수 -> axios 함수로 변경

//vessel-company-list.tsx

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

export const VesselCompanyList = () => {
  const [vesselList, setVesselList] = useState([]);
  const [userInput, setUserInput] = useState("");

  const companyList = () => {
    axios
      .get("..........")
      .then((res: any) =>
        setVesselList(res.data.KR.companies.concat(res.data.GL.companies))
      );
  };

  useEffect(() => {
    companyList();
  }, []);

  const handleChange = (e) => {
    setUserInput(e.target.value);
  };

  const findName = vesselList.filter((word: any) =>
    word.name.toLowerCase().includes(userInput)
  );
  
   return (
    ...
    <input
    type="text"
    name="search"
    id="search"
    placeholder="Search"
    onChange={handleChange}
    />
    ...
    {findName.map((person: any, personIdx) => (...)                               
    ...
    )}
  )
}

> axios

fetch함수만 써오던 중 개발자 분이 알려주신 axios함수를 공부하여 적용해 보았다.

Fetch API보다 Axios가 더 좋은 점
여러 장점들 중 나에게 확 와닿는 장점은 이 세가지이다.

  • 구형브라우저를 지원
    (Fetch API의 경우는 polyfill이 필요하다고 한다.)
  • Node.js에서의 사용
  • JSON 데이터 자동변환
    ( .then((res) => res.json())을 적지 않아도 된다!! )
//fetch 함수
fetch("..........")
      .then((res) => res.json())
      .then((res) => setVesselList(res.KR.companies.concat(res.GL.companies)));

//axios 함수
 axios
     .get("..........")
     .then((res: any) =>
      setVesselList(res.data.KR.companies.concat(res.data.GL.companies))
      );
  • (res: any) : axios 함수를 사용 시 typescript가 더욱 엄격히 적용된다는 느낌을 받았다. 발생한 에러를 res에 :any를 추가하여 해결하였다.

  • axios함수로 변경하고 cannot read property 'companies' of undefined 에러의 원인을 찾느라 30분 정도 걸렸는데 해결책은 생각보다 간단하였다.

  • 같은 데이터를 받아오더라도 fetchaxios일때 받아오는 데이터 형식이 달랐다!

  • fetch함수는 res.KR.companies
    axios함수는 data란 key값이 추가되어있다. res.data.KR.companies

profile
비전공으로 일식 쉐프가 되었듯, 배움에 겸손한 프론트엔드 개발자가 되겠습니다 :)

0개의 댓글