
사진출처 : 마켓컬리
(1-1) Mock Data를 사용해야 하는 이유?
프론트앤드 개발을 진행하다보면 UI 구성에 필요한 백엔드 API가 완성되지 않은 상황에서 개발을 진행해야 하는 상황이 생기는 경우가 있다. 이때 무작정 백엔드 API만 기다리는 것이 아닌 데이터가 의도대로 들어올것을 대비해서 UI가 구현되는지 확인해봐야 한다.
특히 Mock Data를 사용하지 않고 실제 데이터가 들어올 부분들을 하드코딩으로 대체하고 작업을 진행하게 된다면 여러 문제가 발생할 수 있다. 그 이유는 개발이 상태에 따라 많이 확장된 상태이므로, 백엔드 API가 완성되고 실제 데이터를 반영하는 작업을 수행할 때 번거로운 상황이 발생될 수 있으며, 실제 데이터에서는 존재하지 않는 값을 토대로 UI를 그렸거나, 반대로 실제 데이터를 기반으로 작업해야 하는 내용이 누락되었을 수도 있기 때문이다.
(1-2) Mock Data를 활용할 시 장점은?
.json 형태의 확장자 파일로 데이터를 생성해야 한다.예시 1 - 여러개의 상품 리스트)

json 코드)
// public/data/recommendData.json
[
{
"id": 1,
"name": "[프레시지] 밀푀유나베",
"discount_rate": 20,
"discounted_price": 13520,
"original_price": 16900,
"is_sold_out": false,
"comments": 9999,
},
{
"id": 2,
"name": "[프레시지] 블랙라벨 스테이크",
"disconut_rate": 22,
"discounted_price": 13962,
"original_price": 17900,
"is_sold_out": false,
"comments": 999,
},
...
]
예시 2 - 상품 상세 페이지)

json 코드)
// public/data/productData.json
{
"id": 3,
"image_url": "https://product-image.kurly.com/product/image/5aed1b86-a2a7-42cd-b404-8ed1e097caef.jpg",
"name": "[프레시지] 밀푀유나베",
"short_description": "꽃처럼 피어나는 전골 요리",
"discounted_price": 13520,
"discount_rate": 20,
"original_price": 16900,
"unit_text": "1팩",
"weight": "850g",
"delivery_type": [
{ "id": 0, "text": "샛별배송" },
],
...
}
참조 사항)
Mock Data 보관 위치)
public
└── data
├── recommendData.json
├── productData.json
└── ...
(3-1) 호출
// http 주소를 이용할 경우
fetch('http://localhost:3000/data/recommendData.json')
// public 폴더의 절대 경로를 이용할 경우
fetch('/data/recommendData.json')
fetch('/data/recommendData.json', {
method: 'GET'
})
GET 으로 받아와야 한다. fetch('/data/recommendData.json', {
method: 'GET'
})
.then(res => res.json())
.then(data => {
setProductList(data);
});
(3-2) 호출 시점
useEffect(() => {
fetch('/data/recommendData.json', {
method: 'GET'
})
.then(res => res.json())
.then(data => {
setProductList(data);
});
},[]);
(3-3) 전체 코드예시
// RecommendList.js
import React, { useState, useEffect } from 'react';
import ProductCard from './ProductCard/ProductCard';
import './RecommendList.scss';
const RecommendList = () => {
// 상품 리스트 상태 관리 (배열)
const [productList, setProductList] = useState([]);
// 상품 리스트 한번만 불러오기
useEffect(() => {
fetch('/data/recommendData.json', {
method: 'GET'
})
.then(res => res.json())
.then(data => {
setProductList(data);
});
},[]);
return (
<div className="recommendList">
<h1>이 상품 어때요?</h1>
// 상품 리스트
<div className="listWrapper">
{productList.map(product => {
return (
<ProductCard
key={product.id}
product={product}
/>
);
})}
</div>
</div>
);
}
export default RecommendList;
요약)