실제 API 없이도 mockAPI와 localStorage를 사용해
데이터를 가져오고, 저장하고, 재사용 할수있다!
1. mockAPI에서 상품 데이터 생성
↓
2. fetch로 상품 데이터 불러오기
↓
3. 받아온 데이터를 localStorage에 저장
↓
4. 앱을 새로 켜도 저장된 데이터로 화면 구성
| 함수 | 역할 |
|---|---|
fetchProducts() | API에서 데이터 받아오기 |
setStorageItem() | 데이터를 localStorage에 저장 |
setupStore() | 받아온 상품 데이터를 저장하는 역할 |
init() | 앱 시작 시 실행되는 초기화 함수 |
// 🔹 API에서 상품 목록 가져오기
const fetchProducts = async () => {
try {
const res = await fetch('https://mockapi.io/products');
const data = await res.json();
return data;
} catch (error) {
console.error('상품 데이터 불러오기 실패:', error);
return null;
}
};
// 🔹 localStorage 저장 함수
const setStorageItem = (key, value) => {
localStorage.setItem(key, JSON.stringify(value));
};
// 🔹 상품 데이터를 저장소에 세팅
const setupStore = (products) => {
setStorageItem('store', products);
};
// 🔹 초기 실행 함수
const init = async () => {
const products = await fetchProducts();
if (products) {
setupStore(products);
// 이 아래에 renderProducts(products) 같은 함수 연결하면 됨!
}
};
// 🔹 앱 시작
init();
mockAPI에서 데이터를 받아오고, localStorage에 저장해서 앱이 새로 시작될 때도 데이터를 재사용할 수 있는 구조!