Last active
October 23, 2023 04:34
-
-
Save passosleo/387d6985b8bd5a328d7005d442cd222f to your computer and use it in GitHub Desktop.
useLocalStorage.ts
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
export function useLocalStorage() { | |
function storeData<T>(key: string, data: T) { | |
try { | |
if (typeof window !== 'undefined') { | |
localStorage.setItem(key, JSON.stringify(data)); | |
return true; | |
} | |
return false; | |
} catch { | |
return false; | |
} | |
} | |
function getStoredData<T>(key: string): T | null; | |
function getStoredData<T>(key: string, defaultData: T): T; | |
function getStoredData<T>( | |
key: string, | |
defaultData: T | null = null, | |
): T | null { | |
try { | |
if (typeof window !== 'undefined') { | |
const item = localStorage.getItem(key); | |
if (!item) return defaultData; | |
return JSON.parse(item) as T; | |
} | |
return defaultData; | |
} catch { | |
return defaultData; | |
} | |
} | |
function deleteStoredData(key: string) { | |
try { | |
if (typeof window !== 'undefined') { | |
localStorage.removeItem(key); | |
return true; | |
} | |
return false; | |
} catch { | |
return false; | |
} | |
} | |
function clearStorage() { | |
try { | |
if (typeof window !== 'undefined') { | |
localStorage.clear(); | |
return true; | |
} | |
return false; | |
} catch { | |
return false; | |
} | |
} | |
return { storeData, getStoredData, deleteStoredData, clearStorage }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment