window.location.state.buttonEnabled always fails check for undefined with ReactJS - javascript

I'm trying to read the value of window.location.state.endButtonEnabled to check for undefined. But when I actually go ahead and check for undefined I get an undefined error at the if condition. In the following code:
constructor(props){
super(props);
if(window.location.state.endButtonEnabled !== undefined){
console.log('endButtonEnabled is: '+ window.location.state.endButtonEnabled );
//Do Something
}
else{
window.location.state = {endButtonEnabled: true};
}
}
Consider the error in the console:
I tried similar variations of this SO answer to no avail. Any suggestions? I'm using the latest version of ReactJS.

There is no "state" property in the window.location object. So window.location.state is undefined the first time you run the check, breaking your code. It doesn't even get to the endButtonEnabled property.
Why are you putting state into window.location anyways? I assume you are trying to manage the state of your component? You shouldn't be doing that inside of window.location, the entire window object is made by the browser and not something you should be altering without good reason. Look at these react docs to better understand how to manage state.

I decided to first check for window.location.state === undefined. This lead to the following solution while using navigate('/path/destination'). Surprisingly navigate() from '#reach/router' preserves window.location.state so I was able to use that when coming back from the next page. So the final code I ended up with for the check is:
if(window.location.state === undefined){
window.location.state = {endButtonEnabled: false}
}
else{
window.location.state = {endButtonEnabled: true}
}
This code does not break when loading the page for the first time. This may not be the ideal way to state manage things, but this way works for me. I guess the takeaway is: do as the docs say, not as I do.

Related

How thoroughly should I check for possible errors in JavaScript?

I've difficulties to understand how far should I normally go with checking and validating data I operate in my code. I'm not even saying about user-input data here, I'm just saying about my own data, the data I know the structure of. For example, I might have some basic function like this:
let someData = [object];
someFunction(newData) {
let newSet = newData.frequency[0];
someData.dataset.chart.data[0].frequency = newSet;
}
Let's say I have someData variable that is used by a chart, and then I also have a function that simply updates the chart data with a new one. newData comes from my database (when user adjust filters and apply them) and someData is the default, initial data everyone sees. Now, my problem is... I foresee the following events:
Someone might change someData using Developers Console, so this variable will no longer hold an object, or won't have properties I address in my code, so it will lead to errors and break my logic entirely.
Someone might call someFunction directly (using console again) with very random data as argument, and this, again, will lead to errors.
Maybe newData received from DB will be somewhat wrong due to some errors on my side or anything, or maybe initial someData will fail initialising (cause it's initialised through a function as well and relies on third party .JS file that also might fail to load one day).
And I'm not even sure I've foreseen all possible events. So my code turns from what you saw above to something "tedious" (in my opinion) like this:
let someData = [object];
someFunction(newData) {
let newSet = typeof newData === "object" &&
newData.frequency ?
newData.frequency[0] : undefined;
let oldSet = typeof someData === "object" &&
someData.dataset &&
someData.dataset.chart &&
someData.dataset.chart.data &&
someData.dataset.chart.data[0] ?
someData.dataset.chart.data[0].frequency : undefined;
// Since using length on undefined will lead to an error, I've to check the type too
if (Array.isArray(newSet) && newSet.length === 5 && oldSet) {
oldSet = newSet;
} else {
throw Error("Dataset update has failed.");
}
}
And even this doesn't guarantee that the newSet of data is the data I expect to see, because maybe I was looking for [1,2,3,4,5] and user managed to insert ["a","b","c","d","e"] via his console and so on. It feels like I can refine this endlessly and it will never be bulletproof plus eventually it's starting to get complicated to understand my own code, that the only thing I wanted to do is to changed old data with the new data. At this point I'm feeling like I'm doing it all wrong. Coding takes way more time and I'm not even sure I'm doing it for good, but at the same time I can't feel the limit when to stop over-validating my code. Please advise.
I would just stick with user input validation. Out of that, it's their problem if they want to screw you things with developper tools. Anyway, those would only stay on their side.
What's important is the validation on your server. The client side input validation is just to make sure everything put by regular user is error free before processing. It also save useless send to server. The server must redo the validation and more because of those screwed people.

Expected null to deeply equal [Array (1)]

just a brief question. I've been struggling to figure out what this error in javascript actually means: "Timed out retrying: expected null to deeply equal [Array (1)]
I'm basically working on a LocalStorage Shopping Cart and my code is actually based on this video: https://www.youtube.com/watch?v=uR3r3GJvQDY&t=417s
It's pretty much very identical. The code perfectly works on my system without any errors but as soon as I upload it to my university's server on which the code undergoes certain tests I receive the above-named error. It also doesn't really indicate in which line of the code the error is happening. My instructor only told me this usually happens when the cart should exist in the localStorage, however, it doesn't which means the localStorage returns NULL to the system.
For reference to the code please check: https://gist.github.com/prof3ssorSt3v3/3e15d06a8128d6ca7deaa831a7a1e52b
So, we basically create a cart called contents and we never remove empty the LocalStorage at any point in the code. How can the LocalStorage return null at some point then and cause the error?
For the init function I have this:
init(){
//check localStorage and initialize the contents of CART.contents
let _contents = localStorage.getItem(cart.KEY);
if(_contents){
cart.contents = JSON.parse(_contents);
}
else{
cart.contents = [];
cart.sync();
}
},
Thank you for your help in advance!

How to solve Type error in an ionic framework

How can I solve this error:
core.js:1449 ERROR Error: Uncaught (in promise): TypeError: Cannot
read property 'slug' of undefined TypeError: Cannot read property
'slug' of undefined
My code:
this.WooCommerce.getAsync("products?filter[category]=" + this.category.slug).then((data) =>{
console.log(JSON.parse(data.body));
well to me this confirms what I first said. you are indeed pointing to a child of an object within an observable (whether you know what observables are or not) (observables sometimes move all the way up the priority list and happen before hydration of any other var).
so here's the precautions I like to take to make sure things don't go badly: splitting things up.
Also, here's a "hack" I like to use on a general basis in order to ensure I can continue my dev cycle unhindered and have a better notion of where things are failing other than just "undefined":
this.category['slug'];
I never go this far but this is also allowed :
this['category']['slug'];
see this is different because it will actually return the undefined instead of failing there at a JS level.
now to me it seems pretty obvious that you need to ascertain this.category.slug in the instant it's being evaluated isn't in a state in it's lifeline prior to it's initialization :
var myFunctionToLogSlug = () => { //here you could pass this.category.slug as an arg but
//that's the same as simply calling in within the body of this method because your
//context (this) is the same, ergo the pointer and timeframe are also the same.
console.log("is this.category.slug empty ? : ", this.category.slug);
return this.category.slug;
};
this.WooCommerce.getAsync(
"products?filter[category]=" + myFunctionToLogSlug()).then(data =>{
console.log(JSON.parse(data.body));
});
once you've ascertained this.category.slug is indeed undefined at the point it is called, you can either move this.WooCommerce.getAsync to a time-place you know this.category.slug to be defined, or move this.category.slug's hydration to the inside of the getAsync.
hope this helps ! :)

Meteor.userId() returns the value of login user but Meteor.user() is undefined in meteor 1.5

Here is the html:
<div>
<span id="login-entrance">{{loginEntranceContent}}</span>
</div>
Here is the client side js code:
loginEntranceContent(){
if (Meteor.userId()==null) {
return 'Log in/Sign up';
} else {
Meteor.user().emails.address;
};
},
Now I am sure that the user is logged in because when I tried Meteor.userId(),it returns the value of the _id of current user. But the Meteor.user() turns out to be undefined. I assume that the Meteor.user() result should automatically updated later. so I waited for a while,but it didn't update neither in my chrome browser.
And I know the problem has something to do with the fact that the DOM rendered before the data is ready. But I don't know what exactly is going on there.
I already went around the forum for answers, there were some similar topic but none had provided a clear explanation and simple solution for it. So I hope it is worthwhile to open a new topic for it.
FYI, to solve it ,I tried to make a method on server side :
Meteor.users.findOne({_id:'this.userId'});
and called it from the client side. it still get the undefined result....
You are making jsut a null check, what about other 'falsy' value checks, you must properly use the code as below,
loginEntranceContent(){
if (!Meteor.userId()) {
return 'Log in/Sign up';
} else if(Meteor.user() && Meteor.user().emails && Meteor.user().emails[0].address){
return Meteor.user().emails[0].address;
} else {
//do something here.
};
},
and as you have not shown us the code to call Meteor method from client, as #Jankapunkt suggested use code as below at server end,
Meteor.users.findOne({_id : this.userId});
Note: Meteor provides a beautiful API for managing User-Accounts

Check localStorage is set to a specific value?

I'd really appreciate some help on this, I really can't see my issue here.
For some reason, sensing whether this data (loggedIn) is stored in localStorage with the value "yes" - I've tried the regular way of seeing if the localStorage is empty.
Here's my current code...
<script>
function checkLoggedIn()
{
if (localStorage.getItem("loggedIn") === null) {
alert("empty");
}else{
$(".topbar").html("<span>Saved Jobs(0)</span><span>Welcome, "+ storedUsername +"!</span>");
alert("working");
}
}
</script>
Then obviously I would call this with a body onload. For some reason, I can physically see the value of the localStorage when passing it as a variable, but checking it seems to not be working in the slightest.
I'm using this to simulate functionality of a user logging in, the rest of the functions to handle registration and logging in work fine to actually set the localStorage - so it's not a case of it not being stored.
Thanks for any help given people, it's really appreciated.

Categories