React : Mock data 가져오기 / 조건부 렌더링
Mock Data 란?
실제 백엔드 API에서 받아온 데이터가 아닌, 프론트엔드 개발자가 필요에 의해 임의로 만든 샘플 데이터입니다. mock data를 만드는 과정에서 백엔드 API에서 보내주는 response가 어떤 형태인지, key-value값을 확인하고 미리 mock data와 백엔드 response의 형태를 맞춰보면서 추후 실제 API를 수월하게 연결 할 수 있습니다.
- mock 데이터의 확장자는 .json입니다. json파일 안에서는 아래와 같이 스트링화 시켜서 작성해야 합니다.
- Mock data는 선언이 아닌, 데이터일 뿐입니다. 그 안에서는 자바스크립트 문법을 쓸 수 없습니다. 순수 데이터 그 자체를 나타낸다고 생각하며 됩니다.
Mock data 예시.
[
{
"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
}
]
Mock data의 위치 : public 폴더 > data 폴더 > commentData.json
경로 - ‘http://localhost:3000/data/commentData.json' || ‘/data/commentData.json'
'http://localhost:3000/ 여기 까지 쓰면 public 폴더까지 들어간 것입니다.
Mock data의 호출.
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;
- 개발자도구 - 네트워크를 통해 서버에서 받아오는 것을 확인할 수 있습니다.
- method get 은 default값이라 안써줘도 되나 post라면 써줘야 합니다.
- fetch 는 유즈이펙트가 아닌 다른곳에서도 사용 가능합니다.
조건부 렌더링 !
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'
})
.then(res => res.json())
.then(data => {
setCommentList(data);
});
},[])
console.log(commentList)
하면
[] , [{},{}] 이렇게 두번 찍히게 됩니다. 처음 렌더링에 [ ]가 뜨고, 렌더링이 완료된 이후 useEffect로 commentList 스테이트에 값이 들어감으로써 재 렌더링 되어 두번 실행되는 것.
중간에 {commentList.map} 이 있었다면 처음 실행 때 undefined.map으로 실행되게 때문에 에러가 나는 경우가 있습니다.
스테이트 접근 자체에 에러가 나기 때문에,
inputData.length > 0 && 이런식으로 조건을 주어서 실행하면 좋습니다 !