Search code examples
typescriptvuejs3vue-composition-api

How to: Vue3 Setup composition API - Declare typescript type of a object ref


Using Vue 3 and composition API with Setup syntax (TypeScript), I would like to declare a ref inside a component detailing informations of an user.

const userData: Ref<User | undefined> = ref({} as User)

if I use this syntax, I have to put all the time a "?" after userData when I want to access if because the data can also be undefined.

<template>
  <div class="pa-4 pt-1">
    <HeaderPage :title="`Administrateurs - ${userData?.email}`" />
    aaaa {{ userData }}
  </div>
</template>

<script setup lang="ts">
import HeaderPage from '@/components/pages/Header.vue'
import { onMounted, ref } from 'vue'
import UserService from '@/api/modules/user'
import { useRoute } from 'vue-router'

import type { Ref } from 'vue'
import type { User } from '@/api/types/user.interfaces'

const route = useRoute()

const loading = ref(false)
const userData: Ref<User | null> = ref({} as User)

onMounted(() => {
  fetchUserData()
})

function fetchUserData() {
  UserService.getUser(route.params.userId as string).then((res) => {
    userData.value = res
    loading.value = false
  })
}
</script>

EDIT tried this:

const userData: Ref<User> = ref()

but I got: enter image description here


Solution

  • Allow userData to be undefined

    const userData = ref<User>() // implicit undefined allowed
    const userDate = ref<User |  undefined>() // or explicit
    

    Only render the component when data is defined

    <HeaderPage v-if="userData" :title="`Administrateurs - ${userData.email}`" />
                   👆