summaryrefslogtreecommitdiff
path: root/hooks/use-local-storage.ts
diff options
context:
space:
mode:
authordujinkim <dujin.kim@dtsolution.co.kr>2025-05-15 01:19:49 +0000
committerdujinkim <dujin.kim@dtsolution.co.kr>2025-05-15 01:19:49 +0000
commit9eb8e80f4f736c4edffa650c685d1f170ca51aa1 (patch)
treecae02173015c806cd5ea92be86938fe3bf14decd /hooks/use-local-storage.ts
parent71f4dd76b57e77676d8886ac0a8b0bd0a7f24e62 (diff)
(대표님) 구매 요청사항 반영한 통합 rfq / 필터 개인화 / po-rfq
Diffstat (limited to 'hooks/use-local-storage.ts')
-rw-r--r--hooks/use-local-storage.ts48
1 files changed, 48 insertions, 0 deletions
diff --git a/hooks/use-local-storage.ts b/hooks/use-local-storage.ts
new file mode 100644
index 00000000..f24c80db
--- /dev/null
+++ b/hooks/use-local-storage.ts
@@ -0,0 +1,48 @@
+"use client"
+
+import { useState, useEffect } from 'react'
+
+export function useLocalStorage<T>(
+ key: string,
+ initialValue: T
+): [T, (value: T) => void] {
+ // State to store our value
+ const [storedValue, setStoredValue] = useState<T>(initialValue)
+
+ // Initialize with stored value or initial value
+ useEffect(() => {
+ try {
+ // Get from local storage by key
+ if (typeof window !== 'undefined') {
+ const item = window.localStorage.getItem(key)
+ // Parse stored json or if none return initialValue
+ setStoredValue(item ? JSON.parse(item) : initialValue)
+ }
+ } catch (error) {
+ // If error also return initialValue
+ console.error('Error reading from localStorage:', error)
+ setStoredValue(initialValue)
+ }
+ }, [key, initialValue])
+
+ // Return a wrapped version of useState's setter function that
+ // persists the new value to localStorage.
+ const setValue = (value: T) => {
+ try {
+ // Allow value to be a function so we have same API as useState
+ const valueToStore =
+ value instanceof Function ? value(storedValue) : value
+ // Save state
+ setStoredValue(valueToStore)
+ // Save to local storage
+ if (typeof window !== 'undefined') {
+ window.localStorage.setItem(key, JSON.stringify(valueToStore))
+ }
+ } catch (error) {
+ // A more advanced implementation would handle the error case
+ console.error('Error writing to localStorage:', error)
+ }
+ }
+
+ return [storedValue, setValue]
+} \ No newline at end of file