mockAPI + localStorage흐름 정리

이희연·2025년 6월 9일

📦 쇼핑몰 프로젝트 – mockAPI + localStorage 흐름 정리

실제 API 없이도 mockAPIlocalStorage를 사용해
데이터를 가져오고, 저장하고, 재사용 할수있다!


✅ 전체 흐름

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();

🧠 왜 localStorage에 저장하나?

  • 새로고침해도 데이터가 유지됨
  • API 호출을 매번 하지 않아도 됨 (속도 ↑)
  • 간단한 캐시(임시 저장소) 역할

✅ 한 줄 요약

mockAPI에서 데이터를 받아오고, localStorage에 저장해서 앱이 새로 시작될 때도 데이터를 재사용할 수 있는 구조!

profile
코린이🌱 / 개인적인 공부기록 공간입니다, 제로베이스부트캠프 수강중...😄

0개의 댓글