vue.jsnativescript-vue

Null value in v-model


I have a Nativescript-Vue app where I make a REST call to return a response to be displayed. It may not always be fully populated, and when that happens I get an error such as:

[Vue warn]: Error in render: "TypeError: null is not an object (evaluating '_vm.office.address.addressLine1')"

Here is the REST response I get from the server:

{
   "officeId":2,
   "name":null,
   "beginDate":[
      2020,
      4,
      18
   ],
   "endDate":null,
   "officeType":null,
   "address":null
}

And here is the Vue code that has problems:

<StackLayout class="nt-input">
   <Label text="Address Line 1" class="m-b-5"/>
   <TextField :editable="!isViewOnly" v-model="office.address.addressLine1"  v-shadow="2" hint="Enter address line 1" class="-border"/>
</StackLayout>

Because the address hasn't been established, it will be null for new records. Is there any way to get this to render so users can populate?


Solution

  • If office.address is null, then accessing office.address.addressLine1 will always result in that error. You have to ensure that address is not null before doing so.

    After fetching the data, you can check if address is null and then setting it to a new empty address object that you need:

    // Make the request
    const office = await fetchOffice()
    
    // Ensure that address is defined
    if (!office.address) {
      office.address = {
        addressLine1: ''
      }
    }
    
    // Now that we have defined all properties on the object, we
    // can assign it to the component instance to make it reactive
    this.office = office
    

    It is important you define any new properties on the object before you assign it to the component otherwise Vue won't make the new properties reactive (read Change Detection Caveats).