개인 공부를 위해 작성했습니다
4주차에 mock data 활용하여 react westagram을 구현하기 위해 공부하던 중
fetch() 함수 사용법에 대해 더 공부하고자 찾아보고 정리한 내용 기록해본다.
.js 파일로 데이터를 분리하는 방법.js 파일은 어떤 데이터인지 알 수 있게 명명한다import해서 사용.js 파일은 데이터를 import 하는 component 바로 옆으로 접근하기 쉬운 곳에 생성한다const COMMENT = [
  {
    id: 1,
    userName: 'wecode',
    content: 'Welcome to world best coding bootcamp!',
    isLiked: true
  },
  {
    id: 2,
    userName: 'yurim45',
    content: 'Hi there.',
    isLiked: false
  },
  {
    id: 3,
    userName: 'april_5',
    content: 'Hey.',
    isLiked: false
  }
];
export default COMMENT;
.json 파일로 데이터를 분리하는 방법⭐.json 파일에 데이터를 담아 fetch 함수를 사용해 데이터를 받아오는 방법public 폴더 > data 폴더 > .jsonhttp://localhost:3000/data/파일명.json 에서 확인 가능[
  {
    "id": 1,
    "userName": "wecode",
    "content": "Welcome to world best coding bootcamp!",
    "isLiked": true
  },
  {
    "id": 2,
    "userName": "yurim45",
    "content": "Hi there.",
    "isLiked": false
  },
  {
    "id": 3,
    "userName": "april_5",
    "content": "Hey.",
    "isLiked": false
  }
]
Web API fetch() 함수를 쓰거나 axios library를 사용한다
- http 통신의 요청과 응답에 대한 이해와 ✨
 - promise 개념에 대한 공부가 더 중요하다✨
 
fetch('api 주소')
  .then(res => res.json())
  .then(res => {
    // data를 응답 받은 후의 로직
  });
fetch('api 주소')
  .then(function(res) {
    return res.json();
  })
  .then(function(res) {
    // data를 응답 받은 후의 로직
  });
GET인 경우설명: 유저 정보를 가져온다.
base url: https://api.google.com
endpoint: /user/3
method: get
응답형태:
    {
        "success": boolean,
        "user": {
            "name": string,
            "batch": number
        }
    }
fetch('https://api.google.com/user/3')
  .then(res => res.json())
  .then(res => {
    if (res.success) {
        console.log(`${res.user.name}` 님 환영합니다);
    }
  });
import React, { Component } from 'react';
class User extends Component {
  componentDidMount() {
    // user id가 props를 통해 넘어온다고 가정
    const { userId } = this.props;
    fetch(`https://api.google.com/user/${userId}`)
      .then(res => res.json())
      .then(res => {
        if (res.success) {
            console.log(`${res.user.name}` 님 환영합니다);
        }
      });
  }
}
POST인 경우설명: 유저를 저장한다.
base url: https://api.google.com
endpoint: /user
method: post
요청 body:
    {
        "name": string,
        "batch": number
    }
응답 body:
    {
        "success": boolean
    }
fetch('https://api.google.com/user', {
    method: 'post',
    body: JSON.stringify({
        name: "april",
        batch: 1
    })
  })
  .then(res => res.json())
  .then(res => {
    if (res.success) {
        alert("저장 완료");
    }
  })
JSON.stringfy() 함수에 객체를 인자로 전달하여 JSON형태로 변환했다.path 말고 query string으로 넘겨줘야 할 수도 있다설명: 유저 정보를 가져온다.
base url: https://api.google.com
endpoint: /user
method: get
query string: ?id=아이디
응답형태:
    {
        "success": boolean,
        "user": {
            "name": string,
            "batch": number
        }
    }
fetch('https://api.google.com/user?id=3')
  .then(res => res.json())
  .then(res => {
    if (res.success) {
        console.log(`${res.user.name}` 님 환영합니다);
    }
  });
    fetch('http://localhost:3000/data/feedData.json')
      .then(res => {
        console.log(res);
        return res.json();
      })
      .then(data => {
        console.log(data);
        this.setState({
          feedData: data,
        });
      });
  }
실제 작성한 코드로 첫번째 .then'의 res와 두번째 .then'의 data를 console.log에서 확인해보았다
첫번째 .then'의 res`
Response Object두번째 .then'의 data`
.then 함수에서 응답 body의 데이터를 받을 수 있다res.status 응답 코드로 확인하면 된다현재까지 react로 작업하고 mock data로 테스트까지 해본 westagram project
아직 갈 길이 멀지만~ 나름 뿌듯??ㅋㅋ 일희일비 중...😅

✅ 목표!