[TIL] 017. React - fetch

홍효정·2020년 10월 25일
0

TIL

목록 보기
20/40

✔ Get methods


fetch(`${API}/Data/Wallpaper/EDITORSPICKSLIDES.json`)
  .then((res) => res.json())
  .then((res) => {
    this.setState({
      editorsPickTagList: res.editorsPickData.TagList,
      editorsPickSlides: res.editorsPickData.Slides,
  });
});

fetch 함수를 사용하여 componentDidMount가 되었을때 editorsPickTagList, editorsPickSlides 변수에 데이터를 setState한다.


✔ Post methods


  handleClickFollow = (id) => {
    const { topCreators } = this.state;
    const index = topCreators.findIndex((topCreators) => topCreators.id === id);
    const selected = topCreators[index];
    const nextTopCreator = [...topCreators];

    fetch("http://ip주소/works/wallpaper/follow", {
      method: "post",
      body: JSON.stringify({
        creator_id: id,
      }),
    })
    .then((res) => res.json())
    .then((res) => {
       nextTopCreator[index] = {
       ...selected,
       followBtn: res.data.followBtn,
     };
     this.setState({
        topCreators: nextTopCreator,
     });
  });
};

follow 버튼을 클릭했을때 클릭한 컴포넌트의 id값을 인자로 받아온뒤 post method를 사용하여 creator_id로 보내준다.

profile
HHJ velog 🍔

0개의 댓글