클래스와 fetch간 연결

KHW·2021년 5월 15일
0

http-server

목록 보기
1/3

주어진 random사용

  1. GET /cats/random50
    Request parameter
    None

Query paramter
None

Response
Success 200

Field name Type Description
data Array 랜덤한 50개의 고양이 사진 목록입니다.

main.js

new App(document.querySelector("#App"));

App.js

class App {
  $target = null;
  data = [];

  constructor($target) {
    this.$target = $target;

    this.searchInput = new SearchInput({
      $target,
      onSearch: keyword => {
        api.fetchCats(keyword).then(({ data }) => this.setState(data));
      },
      onRandom : ()=>{
        api.randomCats().then(({data})=> console.log(data));
      }
    });

    this.searchResult = new SearchResult({
      $target,
      initialData: this.data,
      onClick: image => {
        this.imageInfo.setState({
          visible: true,
          image
        });
      }
    });

    this.imageInfo = new ImageInfo({
      $target,
      data: {
        visible: false,
        image: null
      }
    });
  }

  setState(nextData) {
    console.log(this);
    this.data = nextData;
    this.searchResult.setState(nextData);
  }
}

중요부분은 추가한 onRandom 부분이다.
api에서 api.randomCats() 실행역할

api.js

const API_ENDPOINT =
  "https://oivhcpn8r9.execute-api.ap-northeast-2.amazonaws.com/dev";

const api = {
  fetchCats: keyword => {
    return fetch(`${API_ENDPOINT}/api/cats/search?q=${keyword}`).then(res =>
      res.json()
    );
  },
  randomCats: ()=>{
    return fetch(`${API_ENDPOINT}/api/cats/random50`).then(res =>
      res.json()
    );
  }
}

randomCats 부분을 추가했다.

searchInput.js


class SearchInput {
  constructor({ $target, onSearch,onRandom }) {
    const $searchInput = document.createElement("input");
    this.$searchInput = $searchInput;
    this.$searchInput.placeholder = "고양이를 검색해보세요.|";

    $searchInput.className = "SearchInput";
    $target.appendChild($searchInput);

    $searchInput.addEventListener("keyup", e => {
      if (e.keyCode === 13) {
        onSearch(e.target.value);
        onRandom();
      }
    });

    console.log("SearchInput created.", this);
  }
  render() {}
}

해당 가져온 onRandom부분을 통해 onRandom()를 실행하고 결과를 받아 현재는 console.log로 출력할 수 있다.

해당결과

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글