
> Today Mission
> 해결
//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가 더 좋은 점
여러 장점들 중 나에게 확 와닿는 장점은 이 세가지이다.
.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분 정도 걸렸는데 해결책은 생각보다 간단하였다.
같은 데이터를 받아오더라도 fetch와 axios일때 받아오는 데이터 형식이 달랐다!
fetch함수는 res.KR.companies
axios함수는 data란 key값이 추가되어있다. res.data.KR.companies