VUEX, what to do when $store.state is null - javascript

When users are not logged into my website, the state of user is set to null.
However, this throws up a lot of issues on some pages where i look to see if this.$store.user
For example, if I were to have a simple check such as
if (this.$store.getters.userInfo.likedProjects.includes(title)) {this.hasLiked = true}
and the user is not logged in (thus, setting the state of user to null by default) I get this error;
_this.$store.getters.userInfo is null
How should I correctly handle this sort of issues so that my console does not get flooded with typescript errors?
My initial idea was to first check if user.loggedIn == true and wrap everything inside of that, but that seems awfully messy just to avoid some errors...

Use optional chaining, which is available in TypeScript 3.7+:
if (this.$store.getters.userInfo?.likedProjects.includes(title)) {
this.hasLiked = true;
}
If userInfo is null or undefined, then the entire statement this.$store.getters.userInfo?.likedProjects.includes(title) will return undefined instead of throwing an error.
If likedProjects may also be null or undefined, then you need to use optional chaining on that property too, i.e.:
if (this.$store.getters.userInfo?.likedProjects?.includes(title)) {
this.hasLiked = true;
}

if(this.$store.getters.userInfo){
if (this.$store.getters.userInfo.likedProjects.includes(title)) {this.hasLiked = true}
}

Related

vue.esm.js:649 [Vue warn]: Error in nextTick: "TypeError: Cannot convert object to primitive value" vue

I'm getting the following warning [Vue warn]: Error in nextTick: "TypeError: Cannot convert object to primitive value" followed by an error TypeError: Cannot convert object to primitive value.
This happens upon setting an object in the store. The data is set in the store correctly, the problem appear to be happening in the renderization of the page after the nextTick is happening.
The console log for the error shows:
at baseSetAttr (vue.esm.js:6811)
at setAttr (vue.esm.js:6786)
at Array.updateAttrs (vue.esm.js:6740)
at patchVnode (vue.esm.js:6312)
at updateChildren (vue.esm.js:6188)
On the file vue.esm.js:6811 I get the following:
function baseSetAttr(el, key, value) {
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
// #7138: IE10 & 11 fires input event when setting placeholder on
// <textarea>... block the first input event and remove the blocker
// immediately.
/* istanbul ignore if */
if (isIE && !isIE9 && el.tagName === 'TEXTAREA' && key === 'placeholder' && value !== '' && !el.__ieph) {
var blocker = function (e) {
e.stopImmediatePropagation();
el.removeEventListener('input', blocker);
};
el.addEventListener('input', blocker); // $flow-disable-line
el.__ieph = true;
/* IE placeholder patched */
}
el.setAttribute(key, value); <--- The error happens here
}
}
I wish I could give more details to this question but I don't have any idea where or why this error is happening directly on my code. I have two pages using the same service, one render it correctly and the other happens this error. I have looked and made sure that both pages are exactly the same but this only happens in one
The answer will seem something extremely stupid but if anyone has an answer on why this happens I will gladly accept the answer.
The problem happens on this line of code on my implemented code:
<template #results="{ items, loading, sort, onSort, orderedHeaders, onColumnOrderChange }">
<order-summary :sort="sort"/>
The component order-summary doesn't have a prop sort. Upon removing of the prop sort everything works correctly.
<template #results="{ items, loading, sort, onSort, orderedHeaders, onColumnOrderChange }">
<order-summary/>
If anyone would have an explanation on why this happens I would gladly accept the answer
I also encountered the same problem. Although I don’t know what caused the problem, I can use
JSON.parse(JSON.stringify(***))
to solved
The reason is this: when parent component pass a prop to child component, and when child component did not receive the prop by registering prop filed, vue will think call prop.toString and put the value to the child's DOM element.
sth like this:
<div sort="[object Object]"></div>
and if the sort prop does have toString method, it will throw the Error you encoutered.
eg:
var a = Object.create(null);
var b = `${a}`, // TypeError: Cannot convert object to primitive value

How to correctly check if a token exists in the store before redirecting

In my application, I want to check if a token exists for the user and, based on this, redirect them somewhere. I have defined the code as follows:
componentDidMount() {
SecureStore.getItemAsync('token').then((val) => {
val ? Actions.link() : null
}
).then(this.setState({ loaded: true }))
}
However, Actions.link() is never called even though the value does exist and can be logged to the console.
How does one correctly check whether a variable exists or not?
I think it might have something to do with the short if/else
can you try:
if (val) {
Actions.link()
}

Check for undefined property in object in EJS in Node.JS

I have an object, called user, which may or may not have subproperties defined. For example, sometimes there is no "pages" object, sometimes you can go user.pages.someothervariable.
I can see in EJS how to check that user exists, but how can I check that user.pages.someothervariable exists without getting a "cannot access property of undefined" error.
I've tried this and typeof, but cannot get it to work.
<% if(locals.user.pages.pageVisits){ %>foo defined<% }else{ %>foo undefined<% } %>
I get this error:
Cannot read property 'pageVisits' of undefined
You can use short-circuiting && --
if(locals.user.pages && locals.user.pages.pageVisits) { /* do sth */ }
If user.pages is falsy, the evaluation won't proceed.
If the chain gets too long, you can try to encapsulate it into a function, like --
function getPage(user) {
return (user && user.pages && user.pages.accountPage)
|| "0"; // a fallback if the left side is falsy
}
You can check if your user has a pages field by running if(local.user.pages). This is because almost any value can be evaluated in if statements in JS. If user.pages is null, then the if statement will return false. If user.pages exists it will return true.
You could do a try-catch to avoid messiness:
var obj = {
test: "hello"
}
try {
console.log(obj.fakeKey.otherFakeKey)
}
catch(ex) {
console.log("Caught")
}

Javascript - Cannot call method 'split' of null

I have a javascript error that occurs on my site, Im pretty sure I know why, but I dont know how to fix it!
here's the error:
Uncaught TypeError: Cannot call method 'split' of null
Here's my JS code:
$(function(e) {
if (document.cookie.indexOf("login") >= 0) {
$("a#loggedInUser").html( $.cookie("login").split("|")[0] );
}
});
I'm just trying to display the username stored in the "login" cookie. Now, im pretty sure the error is because the value returned sometimes isn't a string, then it doesn't have the split method, so it causes this error.
How can I fix that? Any ideas?
Thanks!
Well you can do something like this to set a default if the value is null.
var login = $.cookie("login") || "";
$("a#loggedInUser").html(login);
Also, if you do that you might not need the document.cookie.indexOf thing.
It's probably the case that $.cookie("login") is not returning a valid string. I think the problem is that it's possible that: document.cookie.indexOf("login") >= 0 is true but $.cookie("login") is still null or undefined. It makes sense to use the same check e.g.:
$(function(e) {
var cookie = $.cookie("login");
if(cookie) {
$("a#loggedInUser").html( cookie.split("|")[0] );
}
});
Check the length of the cookie. This way you validate two things at once.
if (document.cookie.indexOf("login") >= 0 && $.cookie("login").length) {
$("a#loggedInUser").html( $.cookie("login").split("|")[0] );
}

Having IE Issues When Passing Object By Ref. and Dynamically Adding Properties

So, I've created a function to do some error checking on an XML file that I recieve from an AJAX call. Part of the validation is that the function then builds out an object for easy access while I process that data into a form. In FF, works like a charm. IE dies with the error:
Object doesn't support this property or method
Here is the function (minus the un-important bits):
function checkReceiveXMLTagString( doc, messageObject, tag ) {
var tag_nodes = doc.getElementsByTagName( tag );
...do some error checking...
messageObject[tag] = tag_str; <-- error occurs on this line
return true;
}
Here is an example of how the function is call:
if ( checkReceiveXMLTagString( messageObject.Name[0], messageObject.Name[0], "First" ) ) {
...process messageObject.Name[0].First...
}
Like I said, FF has no issues. Safari loads the pages as well. IE has issues.
Thanks!
Looks like something is making messageObject be null or undefined
If the error is on this line:
messageObject[tag] = tag_str;
Then, the only two ways I know of that that can cause an error are:
messageObject is not an object that you can set properties on (null or undefined are the most likely ways that would happen)
tag is null or undefined
Since I see that your code calls this function hundreds of times so you can't effectively just break on it, I'd suggest you put in some defensive coding to check for those conditions and output something to the debug console to identify what the state is when the problem occurs. You can even trigger a conditional breakpoint with code like this:
if (!messageObject || !tag) {
debugger;
}
In the toughest cases, you can put an exception handler around it and break when the exception is thrown:
try {
messageObject[tag] = tag_str;
} catch(e) {
debugger;
}
Both of these will allow you to capture the condition in the debugger and examine all your parameters at the time of the error.

Categories