diff options
author | Anton Tananaev <anton@traccar.org> | 2022-05-08 11:48:09 -0700 |
---|---|---|
committer | Anton Tananaev <anton@traccar.org> | 2022-05-08 11:48:09 -0700 |
commit | 2352071211b61c10fa5bf5736baaff7809d18bf0 (patch) | |
tree | 743e4adc1cc35fb3585b912daaa8719ae5757f60 /modern/src/common/util/usePersistedState.js | |
parent | 044733ff543156d76437daae8edb66850d785ac9 (diff) | |
download | trackermap-web-2352071211b61c10fa5bf5736baaff7809d18bf0.tar.gz trackermap-web-2352071211b61c10fa5bf5736baaff7809d18bf0.tar.bz2 trackermap-web-2352071211b61c10fa5bf5736baaff7809d18bf0.zip |
Organize common code
Diffstat (limited to 'modern/src/common/util/usePersistedState.js')
-rw-r--r-- | modern/src/common/util/usePersistedState.js | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/modern/src/common/util/usePersistedState.js b/modern/src/common/util/usePersistedState.js new file mode 100644 index 00000000..8bc4401f --- /dev/null +++ b/modern/src/common/util/usePersistedState.js @@ -0,0 +1,18 @@ +import { useEffect, useState } from 'react'; + +export const savePersistedState = (key, value) => { + window.localStorage.setItem(key, JSON.stringify(value)); +}; + +export default (key, defaultValue) => { + const [value, setValue] = useState(() => { + const stickyValue = window.localStorage.getItem(key); + return stickyValue ? JSON.parse(stickyValue) : defaultValue; + }); + + useEffect(() => { + savePersistedState(key, value); + }, [key, value]); + + return [value, setValue]; +}; |