Vue.js Cannot read property 'length' of null

I am no expert on Vue.js, but the following applies to JS in general.


If socialiteLogins is null or undefined, you can't read the length property of it. That only can be read if socialiteLogins is an array, object, or function. That is why you get the message:

Cannot read property 'length' of null

If socialiteLogins is undefined or an empty array, socialiteLogins !== null. However, socialiteLogins == null (Note that this is using loose comparison).

If socialiteLogins is an empty array, it is still truthy. v-show will regard it as true.

The combination of these facts is making your code not work.


In your case, I think this will work:

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

How it works:

The JS && operator evaluates the first statement; if it is truthy, it returns the value of the second statement. If the first statement is falsy, it returns its value.

v-show coerces the result of the expression to a boolean.

If socialiteLogins is undefined or null, it returns that value, which is coerced to false.

If socialiteLogins is an empty array, socialiteLogins is truthy, so && returns the second statement; socialiteLogins.length will be 0. That will be coerced to false as well.

If socialiteLogins is an array with contents, socialiteLogins will be truthy, and socialiteLogins.length will be a non-zero number, which will be coerced to true.


@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: []
    }
},