mock data 활용하여 상품 상세페이지를 구현하기 위해 공부하던 중
fetch() 함수 사용법에 대해 더 공부하고자 찾아보고 정리한 내용을 기록해본다.
UI를 구현하다 보면 API가 나오기 전에 페이지가 먼저 나오는 경우가 많은데,
이 때 프론트엔드 개발자는 API가 나오기만을 기다리는게 아닌 mock data
즉, 샘플 데이터를 만들어서 내가 만든 화면에서 데이터가 어떻게 나타나는지를
미리 테스트하며 개발을 진행한다.
mock data를 잘 만들어 둔다면, 백엔드와 실제 연결할 때도 수월하게 작업할 수 있을 뿐만 아니라 자료의 형태가 구체적으로 특정되기 때문에 소통에도 도움이 된다
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;
[
{
"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
}
]
백엔드로부터 데이터를 받아오려면 API를 호출하고 데이터를 응답받는다
이 때 자바스크립트 Web API fetch() 함수를 쓰거나 axios library를 사용한다
API든 library든 어느것을 사용해도 괜찮지만, 중요한 것은
http 통신의 요청과 응답에 대한 이해와 promise 개념에 대한 공부가 더 중요하다
fetch('api 주소')
.then(res => res.json())
.then(res => {
// data를 응답 받은 후의 로직
});
fetch('api 주소')
.then(function(res) {
return res.json();
})
.then(function(res) {
// data를 응답 받은 후의 로직
});
fetch() 함수에서 default method는 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, { useEffect } from 'react';
function User(props) {
useEffect(() => {
// user id가 props를 통해 넘어온다고 가정
const { userId } = props;
fetch(`https://api.google.com/user/${userId}`)
.then(res => res.json())
.then(res => {
if (res.success) {
console.log(`${res.user.name} 님 환영합니다`);
}
});
}, [props.userId]);
return <div>User 컴포넌트</div>;
}
export default User;
path 말고 query string으로 넘겨줘야 할 수도 있다.
API 명세
설명: 유저 정보를 가져온다.
base url: https://api.google.com
endpoint: /user
method: get
query string: ?id=아이디
응답형태:
{
"success": boolean,
"user": {
"name": string,
"batch": number
}
}
API호출
fetch('https://api.google.com/user?id=3')
.then(res => res.json())
.then(res => {
if (res.success) {
console.log(`${res.user.name}` 님 환영합니다);
}
});
POST인 경우에는 fetch() 함수에 method 정보를 인자로 넘겨주어야 한다
API 명세
설명: 유저를 저장한다.
base url: https://api.google.com
endpoint: /user
method: post
요청 body:
{
"name": string,
"batch": number
}
응답 body:
{
"success": boolean
}
**API호출
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("저장 완료");
}
})
두 번째 인자에 method와 body를 보내주어야 한다
method는 post
body는 JSON형태로 보내기 위해 JSON.stringfy() 함수에 객체를 인자로 전달하여 JSON형태로 변환했다.