프론트엔드 개발을 진행하려하는데 필요한 백엔드 API가 미완성 되었을 수도 있다.
이러한 경우에는 백엔드에서 API가 완성될때까지 무작정 기다리는 게 아니라, mock data를 만들어 데이터가 들어오는 상황을 미리 대비하고 데이터에 맞게 UI가 의도한대로 구현되는지 먼저 확인해야 한다.
특히나 프로젝트를 진행하는 경우 백엔드 API 유무에 상관없이 화면에 데이터를 예쁘게 보여주는 것이 프론트엔드 개발자로서 가져야 할 책임감이다.
또한 mock data를 만드는 과정에서 백엔드 API에서 보내주는 response가 어떤 형태인지, key-value값을 확인하고 미리 mock data와 백엔드 response의 형태를 맞춰보면서 개발을 진행한다면 추후 실제 API를 훨씬 수월하게 연결할 수 있다.
json
파일로 만들어줘야 한다.commentData.json
[
{
"id": 1,
"userName": "wecode",
"content": "Welcome to world best coding bootcamp!",
"isLiked": true
},
{
"id": 2,
"userName": "joonsikyang",
"content": "Hi there.",
"isLiked": false
},
{
"id": 3,
"userName": "jayPark",
"content": "Hey.",
"isLiked": false
}
]
public
폴더 > data
폴더 > commentData.json
index.html
이 요청된다.[https://naver.com](https://naver.com)
→ 로 접근하면 naver.com에 연결되어있는 서버 컴퓨터의 폴더에 접근해서 index.html
을 가져오는 것public
폴더이다.http://localhost:3000
) public
폴더에 들어가는 것과 동일하다.public/data/commentData.json
파일을 만들어두면, 서버 url을 통해 해당 파일에 접근할 수 있다.http//localhost:3000/data/commentData.json
을 브라우저 주소창에 입력하면 우리가 작성해 둔 데이터가 응답으로 오는 것을 볼 수 있다.http://localhost:3000/data/commentData.json
주소를 입력하여 확인해볼 수 있다.(port number 3000은 변동될 수 있습니다. 에러가 나는 경우 확인해볼 것)http://localhost:3000/data/commentData.json
를 API 주소로 생각하고 http 요청을 통해서 API 요청을 보내고 응답을 받아본다.commentList.js
import React, { useState, useEffect } from 'react';
import Comment from './Comment/Comment';
import './CommentList.scss';
function CommentList() {
const [commentList, setCommentList] = useState([]);
useEffect(() => {
fetch('http://localhost:3000/data/commentData.json', {
method: 'GET' // GET method는 기본값이라서 생략이 가능합니다.
}) // 예시코드에서는 이해를 돕기 위해 명시적으로 기입해뒀습니다.
.then(res => res.json())
.then(data => {
setCommentList(data);
});
},[])
return (
<div className="commentList">
<h1>Main Page</h1>
<ul>
{commentList.map(comment => {
return (
<Comment
key={comment.id}
name={comment.userName}
comment={comment.content}
/>
);
})}
</ul>
</div>
);
}
export default CommentList;
fetch
함수를 사용한다.fetch
함수는 첫번째 인자로 http 요청을 보낼 API주소, 두번째 인자로 요청을 보낼때의 옵션들을 객체형태로 받는다.GET
method를 활용해 요청을 보냈다.setCommentList
함수를 사용하여 commentList
state 를 응답 받은 값으로 바꿔준다.