mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-08 23:28:25 +00:00
26 lines
604 B
TypeScript
26 lines
604 B
TypeScript
import { useEffect, useState } from "react";
|
|
|
|
type TPersisntentStateReturn<T> = [T, (val: T) => void];
|
|
|
|
export const usePersistentState = <T>(
|
|
initialValue: T,
|
|
persistenceKey: string
|
|
): TPersisntentStateReturn<T> => {
|
|
const [val, setVal] = useState<T>(initialValue);
|
|
|
|
useEffect(() => {
|
|
const temp = localStorage.getItem(persistenceKey);
|
|
if (temp) {
|
|
const { key } = JSON.parse(temp);
|
|
setVal(key);
|
|
}
|
|
}, []);
|
|
|
|
const setState = (state: T) => {
|
|
localStorage.setItem(persistenceKey, JSON.stringify({ key: state }));
|
|
setVal(state);
|
|
};
|
|
|
|
return [val, setState];
|
|
};
|