Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js Cannot read property 'length' of null

If I do this:

<div class="panel panel-default" v-if="socialiteLogins !== null">

The panel doesn't hide. If I check socialiteLogins === null alone, or with ==, they both return that the object isn't null. It's definitely null though. If I dump it on the page, I get [] as the result. It's an empty json object. So if I try this:

<div class="panel panel-default" v-if="socialiteLogins.length !== 0">

The panel still doesn't hide and I get this error:

Cannot read property 'length' of null

But If I do this:

<div class="panel panel-default" v-if="socialiteLogins !== null && socialiteLogins.length !== 0">

It hides the panel perfectly with no warnings on initial load but when I update the socialiteLogins variable later I get the length warning if it ever returns an empty json object again. Any idea why?

Edit:

Adding to it... if I do this:

<div class="panel panel-default" v-show="socialiteLogins">

It shows on initial load even though there are none, but if I remove them after the page loads it properly hides the panel. So the only issue appears to be the initial loading where it's not properly detecting that there are no records.

like image 544
Citizen Avatar asked Nov 23 '16 00:11

Citizen


1 Answers

@RyanZim's answer helped. Here's the solution in case anyone else comes here by search in the future.

The issue arises from the initial state of the data. For instance, I had this:

data: function() {
    return {
        socialiteLogins: null
    }
},

Which works for !== null but not for checking .length. Later when it returns an empty object, .legnth will work but not null.

So the solution is keeping it the proper type the entire time so that I can run a consistent check:

data: function() {
    return {
        socialiteLogins: []
    }
},
like image 185
Citizen Avatar answered Sep 20 '22 21:09

Citizen