Skip to content

Next.jsμ—μ„œ useLocalStorag μ‚¬μš© μ‹œ μ—λŸ¬κ°€ λ°œμƒν•˜λŠ” 문제 #91

@suhyeoonn

Description

@suhyeoonn

Next.jsμ—μ„œλŠ” μ„œλ²„ μ‚¬μ΄λ“œ λ Œλ”λ§(SSR)κ³Ό ν΄λΌμ΄μ–ΈνŠΈ λ Œλ”λ§μ„ λͺ¨λ‘ μˆ˜ν–‰ν•˜λŠ”λ°, createLocalStorageManager ν•¨μˆ˜μ—μ„œ LocalStorage μΈμŠ€ν„΄μŠ€λ₯Ό 생성할 λ•Œ ν΄λΌμ΄μ–ΈνŠΈ ν™˜κ²½μ΄ μ•„λ‹ˆλ©΄ μ—λŸ¬λ₯Ό λ°˜ν™˜ν•˜λ„λ‘ λ˜μ–΄ μžˆμ–΄, SSR μ‹œ 500 μ—λŸ¬κ°€ λ°œμƒν•©λ‹ˆλ‹€.
μ„œλ²„ μ‚¬μ΄λ“œ λ Œλ”λ§ μ‹œμ—λŠ” λΈŒλΌμš°μ € API인 localStorageλ₯Ό μ‚¬μš©ν•  수 μ—†μœΌλ―€λ‘œ, μ„œλ²„ μ‚¬μ΄λ“œμ—μ„œ LocalStorage μΈμŠ€ν„΄μŠ€κ°€ μƒμ„±λ˜μ§€ μ•Šλ„λ‘ μ˜ˆμ™Έ μ²˜λ¦¬κ°€ ν•„μš”ν•©λ‹ˆλ‹€.

μ—λŸ¬ λ‚΄μš©

 β¨― src/lib/hooks/useLocalStorage.ts (102:13) @ new LocalStorage
 β¨― Error: localStorage is not available in this environment. Please ensure you are running this code in a browser.
    at new LocalStorage (./src/lib/hooks/useLocalStorage.ts:89:19)
    at createLocalStorageManager (./src/lib/hooks/useLocalStorage.ts:58:21)
    at useLocalStorage (./src/lib/hooks/useLocalStorage.ts:21:74)
    at Home (./src/app/page.tsx:32:90)
digest: "4014735887"
  100 |     if (!validators.isClient()) {
  101 |       console.log("server call");
> 102 |       throw new Error(
      |             ^
  103 |         "localStorage is not available in this environment. Please ensure you are running this code in a browser."
  104 |       );
  105 |     }
 GET / 500 in 241ms

ν›… μ‚¬μš© μ½”λ“œ

"use client";

export default function Home() {
  const [user] = useLocalStorage<IUser | null>("user", null);
  const [token] = useLocalStorage("token", "");
  console.log(token);
  // ...

λ¬Έμ œλ˜λŠ” λΆ€λΆ„

const useLocalStorage = <T>(key: string, initialValue: T) => {
  const storageManager = useRef(createLocalStorageManager<T>(key));
 // ...
}

const createLocalStorageManager = <T>(key: string) => {
  const storage = new LocalStorage(); //<- μ„œλ²„ μ‚¬μ΄λ“œ λ Œλ”λ§ μ‹œ μ—λŸ¬ λ°œμƒ
  // ...
}

ν•΄κ²° λ°©μ•ˆ

const createLocalStorageManager = <T>(key: string) => {
  const storage = validators.isClient() ? new LocalStorage() : null; // <- ν΄λΌμ΄μ–ΈνŠΈ ν™˜κ²½μ΄ 아닐 경우 null λ°˜ν™˜
}

개인 ν”„λ‘œμ νŠΈμ—μ„œ 문제 ν•΄κ²°ν–ˆλ˜ μ½”λ“œ κ³΅μœ λ“œλ¦½λ‹ˆλ‹€!
suhyeoonn/book-rating-frontend@faf68ef

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions