javascript / beginner
Snippet
Safeguarding Deep Nested Profile Data Access with Optional Chaining in Vue
Optional chaining (?.) stops evaluation and returns undefined if a reference is nullish (null or undefined), preventing TypeError crashes when accessing deeply nested properties. When paired with nullish coalescing (??), it provides a clean fallback for asynchronous state that hasn't fully loaded in Vue.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { ref, computed } from 'vue';const userData = ref({name: 'Sarah',account: null});const userCity = computed(() => {return userData.value.account?.address?.city ?? 'City Not Provided';});
vue
Breakdown
1
const userData = ref({
Creates a reactive object where nested structures like account might initially be null.
2
const userCity = computed(() => {
Derives a safe display value from the nested data structure.
3
return userData.value.account?.address?.city ?? 'City Not Provided';
Safely navigates through account and address without throwing an error if account is null, defaulting to a fallback string.