2024-04-16 13:04:00 +02:00
|
|
|
'use client'
|
|
|
|
|
2024-07-26 14:16:59 +02:00
|
|
|
import { type Dispatch, type SetStateAction, useEffect, useState } from 'react'
|
2024-04-16 13:04:00 +02:00
|
|
|
|
|
|
|
function parse(value: string) {
|
|
|
|
try {
|
|
|
|
return JSON.parse(value)
|
|
|
|
} catch {
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function usePersistentState<T>(
|
|
|
|
key: string,
|
|
|
|
initialState?: T | (() => T)
|
|
|
|
): [T, Dispatch<SetStateAction<T>>] {
|
|
|
|
const [state, setState] = useState<T>(initialState as T)
|
|
|
|
|
|
|
|
function changeValue(state: SetStateAction<T>) {
|
|
|
|
setState(state)
|
|
|
|
localStorage.setItem(key, JSON.stringify(state))
|
|
|
|
}
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const stored = localStorage.getItem(key)
|
|
|
|
|
|
|
|
if (!stored) {
|
|
|
|
setState(initialState as T)
|
|
|
|
localStorage.setItem(key, JSON.stringify(initialState))
|
|
|
|
} else {
|
|
|
|
setState(parse(stored))
|
|
|
|
}
|
|
|
|
}, [initialState, key])
|
|
|
|
|
|
|
|
return [state, changeValue]
|
|
|
|
}
|