cannot read property 'push' of null - javascript

I have a page which works on my localhost.. when I put t on a remote server, it gave an error. the code which returns the error is
var $app_list = localStorage.getItem('LsAppList');
var AppListJson = JSON.parse($app_list);
AppListJson.push({
"extapp_id": appdetail.get("addAppId"),
"desc": appdetail.get("addAppName"),
"device_no": appdetail.get("devicenoValue"),
"validation_key": appdetail.get("activationkeyValue")
});
the console log is
Uncaught TypeError: Cannot read property 'push' of null
addToJson EncigoHome.js:126
n.extend.trigger kendo.mobile.min.js:9
s.extend._release kendo.mobile.min.js:15
i._userEvents.o.UserEvents.tap kendo.mobile.min.js:15
n.extend.trigger kendo.mobile.min.js:9
l.extend.notify kendo.mobile.min.js:13
u.extend._trigger kendo.mobile.min.js:13
u.extend.end kendo.mobile.min.js:13
l.extend._eachTouch kendo.mobile.min.js:13
l.extend._end kendo.mobile.min.js:13
arguments.length.t.(anonymous function) kendo.mobile.min.js:10
b.event.dispatch jquery-1.9.1.js:9593
v.handle

localStorage is per domain (more specifically same origin). The localStorage associated with the remote domain does not have access to the values stored in the localStorage associated with your localhost.
You should check to see if there is a stored value and fallback to a default one or treat the error:
var $app_list = localStorage.getItem('LsAppList');
var AppListJson = $app_list != null ? JSON.parse($app_list) : [];
//...
More verbose:
var $app_list = localStorage.getItem('LsAppList'),
AppListJson;
if ($app_list != null) {
AppListJson = JSON.parse($app_list);
} else {
// treat no LsAppList stored case
// you could show a message or set it to a default value
AppListJson = [];
}
This "no previously stored data" scenario will happen whenever the user clears his browser data or switches browsers/devices as well, so it must be treated properly.
The root cause of the error, as you've probably figured out already, is that localStorage.getItem(key) returns null when no value is stored for the given key in the current domain. Then JSON.parse(null) === null and null.push() throws.
Just as a nitpick, I'd suggest reviewing your variables naming:
Don't use PascalCase naming for non-constructors.
Don't mix camelCase with underline naming conventions.
Recommended read: Idiomatic.js naming.
And also, AppListJson is not JSON, it is a native array. JSON can only exist in string context, that is, your $app_list is JSON. More in-depth explanation about JSON/not JSON: There's no such thing as a "JSON Object"

The .push() method can only be used on arrays.
It seems that you don't have the item stored in localStorage, which is why it is returning null

Related

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

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}
}

browser-inconsistent unexpected "undefined" string when using object destruction

When I am trying out some object destruction syntax in some browser consoles, something unexpected happened.
Firstly I entered
action = {
type: "SET_APPS_UI_REVERT",
device: 23456,
managedApps: "12345"
}
and then
( { type, status, appsInfo, device,managedApps,appName } = action);
lastly
status
So both chrome and firefox decided to give me an "undefined" that is a string, rather than a undefined value, while edge would give me an usual undefined. However, when I typed
const { type, status, appsInfo, device,managedApps,appName } = action
and then
status
in edge, it gives me a "" rather than undefined.
Is this results of some browser inconsistency? Or actually some bugs?
Screenshots are below
chrome-66-0-3359-181-no-const.PNG
edge-41-16299-402-0-with-edgehtml-16-16299-no-const.PNG
edge-41-16299-402-0-with-edgehtml-16-16299-with-const.PNG
firefox-60-0-1-no-const.PNG
Using the following syntax:
( { type, status, appsInfo, device,managedApps,appName } = action);
You are explicitly saying "destructure action.status to the existing variable status.
If you don't already have a variable called status in the local scope then it will attempt to assign action.status to the window.status property. This property only accepts a string, so when action does not have a status property, you've effectively done this:
window.status = undefined;
Since window.status coerces to a string, when this is read back you get window.status === "undefined";.
Even though this doesn't have any effect on the statusbar in Firefox, it still exhibits the behaviour.
Your second part is expected behaviour also:
const { type, status, appsInfo, device,managedApps,appName } = action
Is different from before because you're declaring a scoped variable called status. This is where the browser differences come in. In Chrome, when you declare const status in devtools, the devtools is considered the "scope" and you can access it after it's declared. In Edge however, you can declare const within Dev Tools, but you can never access the value. Reference.
So in Edge, you get this kind of behaviour:
{
const status = action.status;
typeof status === "undefined"; // true
}
status; // The value of window.status. const status is out of scope

How can i override the event variable in jquery

On click of document anywhere by default, it is coming as false
I want to change it to true how can I do that..?
jQuery(document).click(function(e) {
console.log(e); //e.target.isConnected = false;
e.target.isConnected = true; //i want to overwrite
--logic--
--logic--
});
I am getting this error:
Uncaught TypeError: Cannot assign to read only property 'isConnected'
of object '[object HTMLAnchorElement]'
My application is in angular 4
The isConnected is property holding a status information and because of that it is read only, and cannot be changed using an assignment.
Node.isConnected
The isConnected read-only property of the Node interface returns a boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the Document object in the case of the normal DOM, or the ShadowRoot in the case of a shadow DOM.

Ionic 2 and JSON Data Addition

I am working with Ionic 2 Storage to persist form data. I save the data like this:
this.storage.set(key, JSON.stringify(formData));
And I retrieve and attempt to update the data like this:
this.getReport(key).then((report) => {
var objReport = JSON.parse(report);
objReport.push(data); //this is the problem
this.storage.set(pk, JSON.stringify(objReport));
});
getReport is just this:
getReport(key) {
return this.storage.get(key);
}
So I know that .push is for arrays and not objects, but I don't think its efficient to do all this conversions because I am dealing with large objects.
My question is: what is the most efficient way to retrieve json from storage and append to it? It makes no sense to me that .parse returns an object if objects do not have a push method like arrays.
Here is the error:
Runtime Error Uncaught (in promise): TypeError: Cannot read property
'push' of undefined TypeError: Cannot read property 'push' of
undefined
what this error means is that, there are no records for that key at this moment.
So, you would have to do a check like this :
this.getReport(key).then((report) => {
var objReport = [];//initialise empty Array
if(report){ //if there is a record in that key location
objReport = JSON.parse(report); //parse the record & overwrite objReport
}
objReport.push(data); //Now this push will happen regardless of report or not
this.storage.set(pk, JSON.stringify(objReport));
});

Javascript breaking on null value of property in Internet Explorer - How can I get IE to ignore this?

Internet explorer is generating this error for the code that follows:
SCRIPT5007: Unable to get value of the property '0': object is null or undefined
for "document.getElementById('files').files[0]"
It's correct that ...files[0] is null, but I don't care, how can I tell IE not to care?
Thanks
var elem = document.getElementById('files'),
file = elem.files && elem.files[0];
This will short-circuit and return undefined if files is undefined, otherwise it will return the first file.
Point of clarification, the error indicates that files is the undefined variable and accessing the property 0 is causing an error. If it were files[0] itself, the expression would just return undefined.
Try...
var file;
if (document.getElementById('files').files){
file = document.getElementById('files').files[0];
}
This is very old but I want to answer for anyone who comes here like me
As Dennis says the error indicates that files is an undefined variable and I'm pretty sure that the problem is IE9 doesn't support files property.
As you can see here IE10 is requiered for.
So try this:
var file;
try{
file = document.getElementById('files').files[0];
}catch(error){
file= null;
}
PS: I apologize for my poor English
var file = document.getElementById('files').files[0] || "undefined";

Categories