File size: 1,071 Bytes
8af739b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'use client'

import { useState, useEffect } from 'react'

// Custom implementation of useKV hook for key-value storage
export function useKV<T>(key: string, defaultValue: T): [T, (value: T) => void] {
  // Initialize state with the default value
  const [value, setValue] = useState<T>(() => {
    // Try to get the value from localStorage on initial load
    if (typeof window !== 'undefined') {
      try {
        const storedValue = localStorage.getItem(key)
        if (storedValue !== null) {
          return JSON.parse(storedValue)
        }
      } catch (error) {
        console.error(`Error reading from localStorage for key "${key}":`, error)
      }
    }
    return defaultValue
  })

  // Update localStorage whenever the value changes
  useEffect(() => {
    if (typeof window !== 'undefined') {
      try {
        localStorage.setItem(key, JSON.stringify(value))
      } catch (error) {
        console.error(`Error writing to localStorage for key "${key}":`, error)
      }
    }
  }, [key, value])

  return [value, setValue]
}

export default useKV