-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
gabrieljablonski
committed
May 13, 2022
1 parent
2a22597
commit f4f3dac
Showing
2 changed files
with
46 additions
and
1 deletion.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,5 @@ | ||
export { }; | ||
import useLocalStorage, { LocalStorageKeys } from './useLocalStorage'; | ||
|
||
export { useLocalStorage }; | ||
|
||
export { LocalStorageKeys }; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import { useState, useEffect, useCallback } from 'react'; | ||
import { hasValue } from 'utils'; | ||
|
||
// eslint-disable-next-line no-shadow | ||
export enum LocalStorageKeys { | ||
EXAMPLE_KEY = 'example-key', | ||
} | ||
|
||
export default function useLocalStorage<DataType = unknown>( | ||
key: LocalStorageKeys, | ||
defaultValue?: DataType, | ||
): [ | ||
DataType | undefined, | ||
React.Dispatch<React.SetStateAction<DataType | undefined>>, | ||
() => void, | ||
] { | ||
const actualKey = `@${process.env.REACT_APP_NAME}:${key}`; | ||
|
||
const inLocalStorage = localStorage.getItem(actualKey); | ||
let actualDefault: DataType | undefined; | ||
try { | ||
actualDefault = JSON.parse(inLocalStorage || '{}').value as DataType; | ||
} catch (err) { | ||
// eslint-disable-next-line no-console | ||
console.log('Local storage error:', err); | ||
} | ||
if (!hasValue(actualDefault)) { | ||
actualDefault = defaultValue; | ||
} | ||
if (!hasValue(actualDefault)) { | ||
actualDefault = undefined; | ||
} | ||
const [value, setValue] = useState(actualDefault); | ||
useEffect(() => { | ||
localStorage.setItem(actualKey, JSON.stringify({ value })); | ||
}, [actualKey, value]); | ||
const remove = useCallback(() => { | ||
localStorage.removeItem(actualKey); | ||
}, [actualKey]); | ||
return [value, setValue, remove]; | ||
} |