A few days, i try to trim the response value in a vue condition.
I need this, when the value is null or empty apply the condition.
<li v-if="item[0].otrodl4.trim() == ''" class="progress-step">
But I got the error
vue.js:597 [Vue warn]: Error in render: "TypeError: Cannot read property 'trim' of null"
The problem is that some values bring only whitespace and no more, that should be considered null or empty.
E.G.
I tried it with filters but I get the same error.
Thanks for read.
Greetings.
Try this:
!item || !item[0] || !item[0].otrodl4 || item[0].otrodl4.trim() == ''
Basically, you have to check that item is defined and not null. And that the first element of that array exists AND that this element has otrodl4 property.
Try this:
item[0] && item[0].otrodl4.trim() == ''
So, the only time it checks if item[0].otrodl4.trim() == '' is if there's a value in the 0 index position of the item array.
It's known as a short-circuit conditional and you can read all about it here.
I have tried with trim() and it is working fine. please try if this can be help to you.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
</head>
<body>
<div id="app">
<!--if only space in text it will display "hello space" else no dsplay. -->
<p v-if="text.trim()==''">hello whitespace {{ text | trim }}</p>
</div>
<script>
new Vue({
el: '#app',
data: function() {
return {
text: ' ' // added only a space
}
}
});
</script>
</body>
</html>
This is a TypeError where the variable you are trying to manipulate is not what it is thought to be by the developer.
Always happen to a language without proper typing.
Therefore, you can do an optional chaining and check the variable is what it is supposed to be first.
ES2020 has allowed us to use optional chaining to type check.
For example,
v-if="!!item?.[0]?.otrodl4?.trim && item?.[0]?.otrodl4?.trim() == ''"
!! is a type conversion to falsy values like null or undefined or empty string to become false.
It makes sure that otrodl4 has a property method trim before calling the method and therefore won't cause TypeError anymore.
Related
My html code contains a <ul id="users"></ul>, which is then populated dynamically with JS code
const li = document.createElement("li");
li.appendChild(document.createTextNode(`${nameInput.value} : ${emailInput.value}`)
I added a button in the html code to delete all users in that <ul>,as such: <button class="btn" id="del-user-list" onClick="deleteUserList()">Delete User List</button>.
My deleteUserList function in the JS code looks like this:
function deleteUserList() {
while (userList.firstChild != "") {
userList.firstChild.remove();
}
}
This works on the surface, however I realize that after the last child, my function will check once again for the value of a child that doesn't exist. I remember from studying C and playing with linked lists that you don't want to dereference a pointer that points to null.
Sure enough, when I look at the console I get
Uncaught TypeError: Cannot read properties of null (reading 'remove') at deleteUserList (main.js:31:25) at HTMLButtonElement.onclick ((index):29:77)
Is this a problem and what can I do about it? I just started playing with Javascript and don't have a good sense of how those things work right now.
Instead of comparing userList.firstChild to an empty string, you should compare it against null or omit the comparison operator entirely:
while (userList.firstChild != null)
// or
while (userList.firstChild)
The latter one works because converting null to a boolean value returns false
null != '' will always be true because userList.firstChild will never be an empty string anyway. It will either be a DOM node or null.
I am fairly new to JavaScript and am going over some code. However there is one bit i am unsure about.
product = product !== null && product[0] !== null && product[0].id || "";
Where product is an array. Could someone please help me understand what this does. Any help would be much appreciated. Many thanks =)
One way to understand what this does it to run it and observe the result.
Here's a JSBin showing 3 examples - which produce a different outcome, depending on the initial value of product - https://jsbin.com/roruvecubi/edit?js,console
To further clarify this with an explanation...
It will attempt to evaluate that all the following premises are true at the same time and re-assign product to the value of id of the first object found (if these are found) or an empty string if otherwise.
product array is NOT null
AND
First element of product array is NOT null
AND
First element of product array is an object containing a truthy key-value pair with key id. I.e. First element could like this:
{
id: "someValue" // product[0].id would be a truthy value in this case
}
AND
If 3.0 is true - assign value of id. If 3.0 is NOT true (id: does not contain a truthy object, array, number, string, true - Google the precise definition of truthy), then just assign empty string "" and thus result will be product = "";
product !== null it checks if product is null if it is it will stop right here and not do the other calculations (this is practiced so you won't get undefined, in this case, hmm null)
product[0] !== null checks if null, so when .id you won't get an error can't find id of undefined / null
let usr = null
console.log(usr.id)
GIVES ERROR Uncaught TypeError: Cannot read property 'id' of null
enter code here
With a few words, these are some practices to check if the VARIABLE has unwanted values to stop the calculations right there and not get errors.
Some prefer to try catch v--
I have this in my template:
<div v-if="errors && errors.name" class="text-danger">{{ errors.name[0] }}</div>
And in the component, I definitely have the errors object defined, it has a name property and that property's value is an array of strings. From dev tools:
Why is the string in the first array member of errors.name not showing then? It looks like the condition errors && errors.name is never true but I can't tell why. I've tried using errors.hasOwnProperty('name') instead but to no avail.
You can't add properties to an object on the fly as Michal mentioned in the comment.
data: function () {
return {
errors: {
name: []
}
}
}
And then with arrays, you cannot assign values directly, use the push method instead and as you initialize it with the above code, you already have an array:
errors.name.push('Please enter a name.');
And lastly in the template, only check the length, as the object is now sure to be present:
<div v-if="errors.name.length > 0" class="text-danger">{{ errors.name[0] }}</div>
I have a projects object like so
projects: {
projectType: {id: 1, title:'something'},
budgetType: {id: 1, title:'something'},
projectStatus: {id: 1, title: 'something'}
}
and im rendering this in the render method.
<td>{this.props.projects.projectType.title}</td>
<td>{this.props.projects.budgetType.title}</td>
<td>{this.props.projects.projectStatus.title}</td>
This works fine, but sometimes the server sends in null when that object is not present as it is not a required field to be entered. So, this throws a "cannot read property of null error". I was using a ternary operator in each case to solve this error which doesnt look really nice. Is there any better way to solve this?
<td>{(this.props.projects.projectType.title)?this.props.projects.projectType.title: ''}</td>
EDIT:
I have a "ProjectList" component which lists all the project rows like so
//in render
<tbody>
{Object.keys(this.props.projects).map(this.renderProject)}
</tbody>
//renderProject Function
<Project key={key} project={this.props.projects[key]}/>
When accessing properties of null Javascript will throw this error. One usual pattern we use is like:
this.props.projects.projectType && this.props.projects.projectType.title
Here the second expression is evaluated only if first one is true. null and undefined are false so the second one won't be evaluated, an no error thrown.
This is because false && <whatever> === false
If projectType is not null, the value of the expression will be equal to the last item in the chain.
This can be chained in fancy ways like:
this && this.props && this.props.projects && this.props.project.projectType;
But it is always recommended to keep these checks inside the javascript file and use some derived attribute for the view.
I don't know if ampersand is a valid token in react expressions. Please refer to other answers on how such cases are handled in React way.
Why not create a simple helper method which accepts the property and returns either the value or an empty string if its null? You would still do the ternary operator but only in one place
Is this the notation to use for Not Equal To in JS, in jquery code
!== OR !=
None of them work
Here is the code I am using
var val = $('#xxx').val();
if (val!='') {
alert("jello");
}
Thanks
Jean
Equality testing in JQuery works no different from "standard" JavaScript.
!= means "not equal to", but !== makes sure that both values have the same type as well. As an example, 1 == '1' is true but not 1 === '1', because the LHS value is a number and the RHS value is a string.
Given your example, we cannot really tell you a lot about what is going on. We need a real example.
.val() is used to retrieve or set values from input in forms mostly, is that what you want to do? If not maybe you mean using .text() or .html().
If that is indeed what you want to do maybe you have your selector wrong and its returning null to you, and null does not equal '', or maybe you actually have data there, like whitespaces. :)
May be you have whitespace in your #xxx node, that why both !== and != failing, you could try following to test non whitespace characters
var val = $('#xxx').val();
if (/\S/.test(val)){
alert('jello');
}
Note: I assume jQuery's .val() won't return null because of this line in jQuery source
return (elem.value || "").replace(/\r/g, "");
If not, you need to do like this
if (val && /\S/.test(val)){
alert('jello');
}
It's both, but the latter is strict on type, see here:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators
It is working with jquery and normal java script.
You should check (alert/debug) your val variable for its value and null.
You should also check $('#xxx').length whether you are getting elements or not otherwise you will get, hence your if condition will be false.