javascript / beginner
Snippet
Reading Stored User Preferences with Safe JSON Parsing
When accessing browser storage such as localStorage, JSON.parse can throw a syntax error if corrupted data is present. Wrapping the parse logic inside a try/catch block inside onMounted ensures the application falls back gracefully to a default state instead of crashing.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { ref, onMounted } from 'vue';const selectedTheme = ref('light');onMounted(() => {try {const storedTheme = localStorage.getItem('app_theme');if (storedTheme !== null) {selectedTheme.value = JSON.parse(storedTheme);}} catch (error) {selectedTheme.value = 'light';}});
vue
Breakdown
1
onMounted(() => {
Executes logic after the Vue component has mounted and browser APIs are accessible.
2
try {
Begins an error-handling block to catch potential parsing failures.
3
selectedTheme.value = JSON.parse(storedTheme);
Parses the stored JSON string safely into JavaScript data.
4
} catch (error) {
Catches any JSON parse error and sets a resilient default fallback value.