๐Ÿงบ ์ตœ๊ทผ ๋ณธ ์ƒํ’ˆ ๊ธฐ๋Šฅ

๋ฐ•์ƒ์€ยท2022๋…„ 9์›” 11์ผ
0

๐Ÿงบ bleshop ๐Ÿงบ

๋ชฉ๋ก ๋ณด๊ธฐ
6/10

next.js์™€ localStorage๋ฅผ ์ด์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

๊ธฐ๋Šฅ ๊ตฌํ˜„์— ๋Œ€ํ•œ ๊ตฌ์ƒ

์ฒ˜์Œ์— ์ด ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•ด์•ผ๊ฒ ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์„ ๋•Œ๋Š” ๋กœ๊ทธ์ธํ•œ ์œ ์ €๊ฐ€ ํŠน์ • ์ƒํ’ˆ์˜ ํŽ˜์ด์ง€์— ๋“ค์–ด๊ฐ”์„ ๊ฒฝ์šฐ๋งˆ๋‹ค DB์— ๊ธฐ๋ก ๋ฐ ์—…๋ฐ์ดํŠธํ•ด์„œ ์ตœ๊ทผ์— ์ ‘๊ทผํ•œ ์ƒํ’ˆ์ด ๋ฌด์—‡์ธ์ง€ ์•Œ์•„๋‚ด๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ๊ตฌํ˜„ํ•˜๋ฉด ๋  ๊ฒƒ์œผ๋กœ ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค.
๊ทธ๋ž˜์„œ ์ถ”๊ฐ€ํ•  ์ฝ”๋“œ๊ฐ€ ๋งŽ๊ณ  ์‹œ๊ฐ„์ด ์ข€ ๊ฑธ๋ฆด๊ฑฐ๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ๋‹ค๋ฅธ ๊ธฐ๋Šฅ์„ ๋ชจ๋‘ ๊ตฌํ˜„ํ•˜๊ณ  ๋งˆ์ง€๋ง‰์— ๊ตฌํ˜„ํ•˜๋ ค๊ณ  ๋ฏธ๋ค„๋†จ๋˜ ๊ธฐ๋Šฅ์ž…๋‹ˆ๋‹ค.

ํ•˜์ง€๋งŒ ๋ง‰์ƒ ๊ตฌํ˜„ํ•˜๋ ค๊ณ  ์ฐพ์•„๋ณด๋‹ˆ ์ƒ๊ฐ๋ณด๋‹ค ๊ฐ„๋‹จํ•˜๊ฒŒ ๊ตฌํ˜„์ด ๊ฐ€๋Šฅํ–ˆ์Šต๋‹ˆ๋‹ค.
๋ฐ”๋กœ localStorage๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ๊ตณ์ด DB์— ์ €์žฅํ•  ๋งŒํผ์˜ ์ •๋ณด๋„ ์•„๋‹ˆ๊ณ , ๋…ธ์ถœ๋˜์–ด๋„ ํฌ๊ฒŒ ์ƒ๊ด€์—†๊ณ , ์‚ญ์ œ๋˜์–ด๋„ ์ƒ๊ด€์—†๋Š” ์ •๋ณด๋ฉด์„œ, ํฐ ์šฉ๋Ÿ‰์„ ์ฐจ์ง€ํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— localStorage or sessionStorage๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒŒ ์ข‹์€ ๋ฐฉ๋ฒ•์ด๋ผ๊ณ  ๋Š๊ผˆ์Šต๋‹ˆ๋‹ค.

๊ธฐ๋Šฅ ๊ตฌํ˜„

์ผ๋‹จ localStorage์— ๋„ฃ์„ ๊ฐ’์€ ์‹๋ณ„์ž, ๋Œ€ํ‘œ ์ด๋ฏธ์ง€ ๊ฒฝ๋กœ, ์ด๋ฆ„ 3๊ฐ€์ง€๋กœ ์ •ํ–ˆ๊ณ , ์ด๋ฆ„์€ watched์ž…๋‹ˆ๋‹ค.
๊ทธ๋ฆฌ๊ณ  ๊ธฐ์กด์— ๋ดค๋˜ ์ƒํ’ˆ์ด๋ผ๋ฉด ์ˆœ์„œ๋งŒ ๋ฐ”๊พธ๊ณ , ์ƒˆ๋กœ ๋ณธ ์ƒํ’ˆ์ด๋ผ๋ฉด ์ถ”๊ฐ€ํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค.

  • localStorage์— ๋ฐฐ์—ด์ด๋‚˜ ๊ฐ์ฒด๋ฅผ ๋„ฃ์„ ๊ฒฝ์šฐ์—๋Š” ๊ฐ•์ œ๋กœ String์œผ๋กœ ๋ณ€๊ฒฝ์‹œ์ผœ์„œ ๋„ฃ๊ธฐ ๋•Œ๋ฌธ์— JSON.stringify()๋ฅผ ์‚ฌ์šฉํ•ด์ฃผ์ง€ ์•Š์œผ๋ฉด [Object]๊ฐ™์€ ํ˜•์‹์œผ๋กœ ๋ฐ์ดํ„ฐ๊ฐ€ ๋“ค์–ด๊ฐ€๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.
    ๋”ฐ๋ผ์„œ ๋„ฃ๊ณ  ๊ฐ€์ ธ์˜ฌ ๋•Œ๋Š” JSON.stringify()์™€ JSON.parse()๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.
export type RecentProduct = {
  idx: number;
  photo: string;
  name: string;
};

useEffect(() => {
  if (!product) return;

  const previousWatched: RecentProduct[] = JSON.parse(
    localStorage.getItem("watched") || "[]"
  );
  if (!Array.isArray(previousWatched)) return;

  let currentWatched: RecentProduct[] = [];
  const targetIndex = previousWatched.findIndex(
    (watched) => watched.idx === product.idx
  );

  // ์ฒ˜์Œ ๋ณด๋Š” ์ƒํ’ˆ์ด๋ผ๋ฉด
  if (targetIndex === -1) {
    const { idx, photo, name, ...rest } = product;
    currentWatched = [{ idx, photo, name }, ...previousWatched];
  }
  // ์ตœ๊ทผ์— ๋ณธ์ ์ด ์žˆ๋Š” ์ƒํ’ˆ์ด๋ผ๋ฉด
  else {
    const target = previousWatched.splice(targetIndex, 1);
    currentWatched = [...target, ...previousWatched];
  }
  
  // ๋ชฉ๋ก์ด 10๊ฐœ๊ฐ€ ๋„˜์œผ๋ฉด ์ž๋ฅด๊ธฐ
  if (currentWatched.length > 10) currentWatched.pop();

  localStorage.setItem("watched", JSON.stringify(currentWatched));
}, [product]);

0๊ฐœ์˜ ๋Œ“๊ธ€