-
Notifications
You must be signed in to change notification settings - Fork 0
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
Showing
1 changed file
with
32 additions
and
0 deletions.
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 |
---|---|---|
@@ -0,0 +1,32 @@ | ||
export const hasLocalStorage = (): boolean => { | ||
return typeof localStorage !== 'undefined'; | ||
}; | ||
|
||
export const LocalStorage = { | ||
/** | ||
* Gets a JSON value from local storage for the given key. | ||
* If either local storage isn't defined or key not found then | ||
* returns undefined. | ||
*/ | ||
get: <T>(key: string): T | undefined => { | ||
if (!hasLocalStorage()) { | ||
return; | ||
} | ||
const value = localStorage.getItem(key); | ||
if (value) { | ||
return JSON.parse(value); | ||
} | ||
return; | ||
}, | ||
/** | ||
* Sets a JSON value in local storage for the given key. | ||
* The value should be JSON serializable. | ||
* For example, not a `Map` or `Set` because those become `{}`. | ||
*/ | ||
set: <T>(key: string, value: T): void => { | ||
if (!hasLocalStorage()) { | ||
return; | ||
} | ||
localStorage.setItem(key, JSON.stringify(value)); | ||
}, | ||
}; |