major697
major697

Reputation: 1862

Vue 3 composition API get value from object ref

I have a ref:

const editItem = ref<object | null>(null)

Here's an example value for it:

{
   id: 1,
   title: 'Harry Potter',
   author: 'J.K. Rowling',
   created: '30-08-2000',
}

If I run console.log(editItem.value), I see this object:

enter image description here

But when I try to read the value's author with console.log(editItem.value.author), then I see this error:

Object is possibly 'null'.

Upvotes: 0

Views: 14046

Answers (2)

tony19
tony19

Reputation: 138276

Since the type of the ref is object | null, it could be null when you access it, leading to a runtime exception. The error message is warning about that possibility for editItem.value.

You could either add a null-check around its access:

if (editItem.value) {
  console.log(editItem.value.author)
}

...or you could simply use optional chaining:

console.log(editItem.value?.author)

But you'll notice that you'll get a different warning about author not being part of the signature for object. One solution is to change the ref's type from object to a specific interface:

interface MyRef {
  id: number;
  title: string;
  author: string;
  created: string;
}

const editItem = ref<MyRef | null>(null)

console.log(editItem.value?.author) ✅

Upvotes: 2

Daniel
Daniel

Reputation: 35684

Cześć Michal

The issue (without seeing the code) seems to be that you are using ref for a object value. While you may find some workaround to get it to work, the simplest way to deal with reactive objects is to use reactive instead of ref.

One additional benefit is that you won't need to use .value when you're getting or setting the object value.

Upvotes: 1

Related Questions