[TIL #44 기업 협업] 배열 데이터 병합하기 (fetch)

Whoyoung90·2021년 4월 21일
0
post-thumbnail

210422 WECODE #44 기업협업 9일차

fetch & concat

> Today Mission

객체 GLKR 안에 있는 각각의 companies 배열들을

하나의 배열로 통합하여 하나의 map함수를 뿌려주고 싶다면?

> 해결

//vessel-company-list.tsx

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

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

  const companyList = () => {
    fetch("..........")
      .then((res) => res.json())
      .then((res) => setVesselList(res.KR.companies.concat(res.GL.companies)));
    //.then((res) => console.log(res));
  };

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

  return (
    ...
    {vesselList.map((person: any, personIdx) => (...)                               
    ...
    )}
  )
}
  • const [vesselList, setVesselList] = useState([]);
    내가 fetch함수를 통해 받아 올 것은 companies: Array이므로
    vesselList의 초기값은 빈 배열[ ]로 받는다!

  • 위 이미지는 people에서 받아오는 .then((res) => console.log(res.KR.companies)); 혹은 .then((res) => console.log(res.GL.companies));의 배열 테이터이다.

  • setVesselList(res.KR.companies.concat(res.GL.companies))
    국내 회사 데이터를 받아오는 setVesselList(res.KR.companies).concat(res.GL.companies)으로 국외 회사 데이터를 추가해주면
    두 객체의 배열값을 하나의 배열로 합칠 수 있다.
profile
비전공으로 일식 쉐프가 되었듯, 배움에 겸손한 프론트엔드 개발자가 되겠습니다 :)

0개의 댓글