Created
May 29, 2026 13:32
-
-
Save cmbaughman/f4ceade2861aea3648b0a8d20552cd7e to your computer and use it in GitHub Desktop.
LocalStorage Sample Best Practices
This file contains hidden or 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
| // localStorage only writes strings | |
| function setItem(key, value) { | |
| try { | |
| localStorage.setItem(key, JSON.stringify(value)); | |
| } catch (e) { | |
| if (e.name === "QuotaExceededError") { | |
| console.warn("Local Storage quota exceeded! Please clear some old entries."); | |
| } | |
| } | |
| } | |
| // localStorage only stores strings not objects so parse! | |
| function getItem(key, fallback = null) { | |
| try { | |
| const value = localStorage.getItem(key); | |
| return value ? JSON.parse(value) : fallback; | |
| } catch { | |
| return fallback; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment