Vue.js Cannot read property 'split' of undefined - javascript

I'm showing page breaks within my vue.js application.
<div class="Message__body__message">
<p v-for="line in message.message.split('\n')" track-by="$index">{{ line }}<br></p>
</div>
But I receive the error:
main.js:7382 [Vue warn]: Error when evaluating expression "message.message.split('\n')": TypeError: Cannot read property 'split' of undefined
But message.message is not empty! I even receive the expected result, so why does it throw this error?

I even receive the expected result, so why does it throw this error?
Because at some stage, it is undefined. Clearly, if you're ultimately getting the result you expect, it's then becoming defined, but that's later.
You could work around it by doing:
v-for="line in (message.message || "").split('\n')"
...but it would probably be better to look at the greater picture of what that code's doing and find out why message.message is undefined at times it's trying to evaluate that.
As Bill Criswell points out in a comment, you might look at using a computed property on your model for that rather than an in-template expression. E.g.:
var vm = new Vue({
// ...your other stuff here...
// Computed properties:
computed: {
messageLines: function() {
return (this.message.message || "").split("\n");
}
}
});
then
v-for="line in messageLines"

The view load when the page is first time load or message.message change.
I believe that you have use vue data in wrong way like this.
data: function(){
return {
message: {}
}
}
Obviously, you have defined message attribute in data, but not define message.message. So first time when it load, message is still empty, it still didn't get your ajax response, so it tells that message.message is undefined. You should change it into this, use nested attribute, to set a legal value.
data: function(){
return {
message: {message: ''}
}
}
You should understand that the view get render at least 2 times, first time use default value you set in data, other time when you change the message, in ajax callback or other situation.

message.message might not be available when vue tried to load it. Request vue to try to load message.message only when message.message is available.
The following worked for me.
<div class="Message__body__message" v-if="message.message">
<p v-for="line in message.message.split('\n')" track-by="$index">{{ line }}<br></p> </div>

Related

Problem function call before re render in vuejs

I have a problem, when I add an element in my bdd and my view client (with $set), a function is called. But I have error for accessing data, with the console.log, I see the new data is added but the data inside the object is not.
This is my error:
vue.esm.js?efeb:610 [Vue warn]: Error in render: "TypeError: Cannot read property 'id' of undefined"
for (var i = 0; i < this.assignments.length; i++) {
var date1 = new Date(date);
var date2 = new Date(this.assignments[i].start);
if (user === this.assignments[i].User.id) {
The error is saying that you are accessing an undefined value in this case the User of this.assignments[i].User is undefined.
Edit : To be sure check every thing
if (this.assignments && this.assignments[i] && this.assignments[i].User && user === this.assignments[i].User.id)
Well..
If I see problem like this, I am always trying to put debugger right after console.log in order to stop executing script. Don't always trust console.logs someone somewhen said.
Probably with that debugger, console.log will show something different, and that's because it's holding reference, so it's filled later. (you will be able to see that in the console)
Anyway...
What You can try to do for sure is
await this.$nextTick() - waiting for next render, then continue
Put it right before your not working code.
If not you can try forbidden technique - to wrap your code in
setTimeout(()=>{
...your code which needs to wait for render
},0)

Able to Get Value in Console, But Undefined When Called From Function in Angular 2 App

I am running into an issue in my Angular 2 app where I'm getting an undefined error that's not making sense to me. What's more perplexing is that, after getting the undefined error, I can effectively check the exact same value in the console and get it with no issues.
First off, here's a version of the function that DOES work:
public getApplicableResult()
{
if (!this.customer || !this.customer.services || !this.customer.services.getAt(0))
{
console.log('Services not available...');
return;
}
else if (this.customer && this.customer.services && this.customer.services.getAt(0))
{
console.log(this.customer.services.getAt(0));
}
When I run this function I get this in the console for my "console.dir" of my object literal:
CustomerServiceDetails
assignments:(...)
authorizations:(...)
If I then click on "assignments" in the console, I get this expanded result:
assignments:
CustomerAssignmentCollection
count:1
items:Array(1)
So all the data is seemingly there and available.
However, if, in my function, if I were to try and access these nested values more directly - such as the value for "count" above, I get an undefined error. That's what I'm not understanding. Perhaps it's something I misunderstand about how the console works. But if seems to me that if I can access the value for this property in the console, then I should be able to access it directly via my function.
Here's an example of the same function, slightly altered to get the result for "count" within assignments, that returns undefined:
public getApplicableResult()
{
if (!this.customer || !this.customer.services || !this.customer.services.getAt(0).assignments)
{
console.log('Services not available...');
return;
}
else if (this.customer && this.customer.services && this.customer.services.getAt(0).assignments)
{
console.dir(this.customer.services.getAt(0).assignments.count);
}
The specific error I get is:
Cannot read property 'assignments' of undefined;
To add some additional info, assignments is not an array, it's a collection.
Two questions here:
1.) Why isn't my first "if" clause handling the 'undefined' error? How could I adjust it to handle the situation better?
2.) Why can I call the first function, get a result, and then drill down from there in the console to get what I need, but if I try and access a more nested part of the object in the function itself, I get undefined as a result?
One additional detail, I was calling this via Angular's ngAfterViewChecked(). So what that should do, even if it's a timing issue, is return the first "if" else clause result until the value is available, and then it should show the result - i.e., it should execute the "else if" block - because AfterViewChecked() keeps checking. But this isn't happening. I'm just getting the undefined result I mentioned above.

Configure javascript to rise error when pass json undefined member?

You have a json object.
By mistake you pass some element (property1) to a function and the value passed doesn't exists...
myFunction (json.propety1); // it must be 'property1' , with r
I'd like to set any configure element to say the browser "I can't pass undefined json properties, rise an error"
I think this is not possible, is't it ?
Thanks in advance
in myfunction you can check for undefined and then do something
like
function myFunction(jsonproperty){
if(jsonproperty === undefined){
//do something with the DOM to pass whatever you wanna say in the browser
}
}
Is that what you were trying to do? You could also throw an exception like this:
throw "json property was undefined"
but you would only see that in some kind of js debugger console. Nowadays all browser have one. Usually accessible with "F12"

I am unable to return an array of a document using an each function in meteor

My html code:
<template name="homeItem">
<li class= "{{selectedClass}}">{{{content}}}</li>
<li class= "tagsBody">{{#each tags}}{{tags}} {{/each}}</li>
</template>
The subscribing to "contents" is being done at the route controller level.
Now the "tags" is an array which is a part of "content" which is a document in a collection named "contentsList".
I have used a homeitem helper function which goes such as this:
JS client code
Template.homeItem.helpers({
'tags':function(){
return contentsList.findOne({_id: this._id}).tags
}
});
The errors that are returned are:
1) Exception in template helper: TypeError: Cannot read property 'tags' of undefined.
2)Uncaught Error: {{#each}} currently only accepts arrays, cursors or falsey values.
3)Exception from Tracker recompute function:TypeError: Cannot read property '0' of null
How can I solve this problem? I am new to programming. So, please forgive me for diverting from any programming conventions. Any help would be hugely appreciated.
contentList.findOne({_id: this._id}) is returning null, so when you try to do null.tags it shows up as undefined.
Make sure that a subscription exists for contentsList and that you can search it. Test this by running contentList.find().fetch() to see what comes back. If nothing comes back, your subscription doesn't exist.

Uncaught TypeError: Cannot read property 'value' of null, need some direction

I have been trying to figure out this particular problem in my developer tools, but I've had no luck thus far. I have an error on one of my js files that says
Uncaught TypeError: Cannot read property 'value' of null
The following error refers to the 1st variable of dt_version below. The particular thing is if I comment out the first line of code. I get the same error on the following variables of offload1 and offload2. The variable is a number that I am trying to get passed over. I run this function on my body when the page loads...onload=updatetotal();
function updatetotal() {
var dt_version = document.getElementById("dt_version").value-0;
var offload1 = document.getElementById("capacity_offload1").value-0;
var offload2 = document.getElementById("capacity_offload2").value-0;
var offload3 = document.getElementById("capacity_offload3").value-0;
}
If a run an if statement looking for document.getElementByID("dt_version");...it defaults to false..so its not being carried over though on the previous page, I can see its input fine with the value in it. What am I missing here guys?
This error means that the id dt_version does not exist. Check your html to make sure it is there:
var dt = document.getElementById("dt_version");
if (dt){
// do your stuff
}else {
console.log("dt does not exist")
}
Another cause for this error may be- as you are calling the javascript function on page load there is a possible chance that your control is not yet completely rendered to the page. A simple solution is just move that control to the beginning of the page. If it doesn't work then an reliable solution is, call the function inside jquery $(document).ready().

Categories

Resources