Last active
February 8, 2024 23:03
-
-
Save emekaorji/4221fe5843589db0d71d422b3cb6a821 to your computer and use it in GitHub Desktop.
A react hook to establish a sync with the electron store with real-time updates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'; | |
function useStoreState<T>( | |
_key: string, | |
_initialValue: T | (() => T) | |
): [T, Dispatch<SetStateAction<T>>]; | |
function useStoreState<T = undefined>( | |
_key: string | |
): [T | undefined, Dispatch<SetStateAction<T | undefined>>]; | |
function useStoreState<T = undefined>( | |
key: string, | |
initialValue?: T | (() => T) | |
) { | |
const [value, setValue] = useState(() => { | |
try { | |
const storedValue = window.electron.store.get(key); | |
return storedValue ? (JSON.parse(storedValue) as T) : initialValue; | |
} catch (error) {} | |
return initialValue; | |
}); | |
const currentKey = useRef(key); | |
useEffect(() => { | |
let _value: T | undefined; | |
if (currentKey.current !== key) { | |
_value = window.electron.store.get(key); | |
currentKey.current = key; | |
setValue(value ?? initialValue); | |
} else { | |
_value = value; | |
} | |
window.electron.store.set(key, _value); | |
}, [initialValue, key, value]); | |
return [value, setValue] as const; | |
} | |
export default useStoreState; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment