Using an object from state that could be null #792
-
Hi, just after an idea on how best to achieve this. I want to store the logged in user as state within a store. So I have a simple app store. interface User {
id: number
firstName: string
}
interface AppState {
user: User | null
}
export const useAppStore = defineStore('app', {
state: (): AppState => ({
user: null
}),
getters: {
authenticated: ({ user }) => user !== null
},
actions: {
async login (email: string, password: string) {
this.user = await http.post('login', { email, password })
}
}
}) On a template that expects a user to be logged in I want to display the users name. <template>
<span>Hello {{ user.firstName }}</span>
</template>
<script lang="ts" setup>
import { useAppStore } from '../store/app'
import { storeToRefs } from 'pinia'
const { user } = storeToRefs(useAppStore())
</script> Now, this works, but I get the following TS warning within the template:
Which makes sense, since I have said that it could be Cheers. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
There shouldn't be anything wrong with this. This is the reason the
We use the In other cases where we cannot be sure that it exists (or want something a bit more bulletproof) we do something like: <!-- Use a ternary -->
<template>
<span>Hello {{ user ? user.firstName : '' }}</span>
</template>
<!-- Use type narrowing within the template -->
<template>
<span v-if="user">Hello {{ user.firstName }}</span>
<span v-else>Not Logged In</span>
</template>
<!-- Use the ! postfix in the script instead -->
<!-- (in some cases using the ! postfix in templates isn't supported depending on your tooling) -->
<script>
const appStore = useAppStore()
const user = computed(() => appStore.user!)
</script> |
Beta Was this translation helpful? Give feedback.
-
In addition to Ben's answer your could use the nullish coalescing operator in your code like so: <template>
<span>Hello {{ user.firstName ?? 'anonymous' }}</span>
</template> |
Beta Was this translation helpful? Give feedback.
There shouldn't be anything wrong with this. This is the reason the
!
operator exists, to quote from https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#non-null-assertion-operator-postfix-We use the
SomeInterface | null
type a lot in our stores, it works fine to use the!
postfix operator in some cases.In other cases where we cannot be sure that it exists (or want something a bit more bulletproof) we do something like: