How to perform null-check before accessing the value in ref() of Vue3?

Viewed 24

I face some errors where sometimes the modelInfo is not available to access.

Note :

modelInfo?.value.model_owner

const summaryItems = ref({
  title: "Model Summary",
  items: {
    "Model Owner": getFullName(modelInfo?.value.model_owner),
  },
});

How do I add a null-check to modelInfo before accessing them ?

I would

do this if I was in the block of codes :

if (modelInfo) {
    ...
}

and this if I was setting the value of the property

modelInfo || '';

... but I wasn't sure what to do in my case/situation

1 Answers

You could use a ternary operator

const summaryItems = ref({
  title: 'Model Summary',
  items: {
    'Model Owner': modelInfo ? getFullName(modelInfo.value.model_owner) : ''
  }
});

In this case if modelInfo is null the Model Owner property will be empty string but can be whatever fallback value you want.

Or maybe a ternary operator on the parent items property

const summaryItems = ref({
  title: 'Model Summary',
  items: modelInfo ? { 'Model Owner': getFullName(modelInfo?.value.model_owner) } : null
});

where items will be null if modelInfo is null

Related