Home > other >  How do you check if an API Object is undefined without getting a console error?
How do you check if an API Object is undefined without getting a console error?

Time:03-24

I'm using JS & AJAX to gather info from a Web-API (for a crypto-mining pool). Almost all of it works perfectly, but with the server the way the developer set it up, when a value is not used, it MIGHT be empty, not 0. Others do have a placeholder value (I'm talking with the dev to give everything a placeholder, but until then, I need some help).

e.g.:

{"version":"0.0.3","statusCode":200,"headers":{"Access-Control-Allow-Headers":"Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Allow-Methods","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Content-Type":"application/json"},"body":{"primary":{"hashrate":{"shared":0,"solo":0},"payments":{"balances":0,"generate":0,"immature":0,"paid":0},"shares":{"shared":{},"solo":{}},"times":{"shared":0},"work":{"shared":0,"solo":0},"workers":{"shared":[],"solo":[]}},"auxiliary":{"hashrate":{"shared":0,"solo":0},"payments":{"balances":0,"generate":0,"immature":0,"paid":0},"shares":{"shared":{},"solo":{}},"times":{"shared":0},"work":{"shared":0,"solo":0},"workers":{"shared":[],"solo":[]}}}}

You can see that under body.primary.shares.shared it is just [] and not a zero value.

Here is part of the script:

function avianDashboard(api, workerAPI) {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", api, true);
    xhr.onload = function () {
        if (this.status === 200) {
            obj = JSON.parse(this.responseText);
            if (typeof (obj.body.primary.shares.shared) === 'undefined') {
                document.getElementById('minerShares').innerHTML = 0;
            } else {
                document.getElementById('minerShares').innerHTML = obj.body.primary.shares.shared.valid;
            }

//Rest of the function works properly so I've omitted it for the sake of sanity

When I run the page, the console.log shows this..

uncaught TypeError: Cannot read properties of undefined (reading 'shared') at XMLHttpRequest.xhr.onload (avian.php:784:61)

and points to this line:

if (typeof (obj.body.primary.shares.shared) === 'undefined') {

I've found a lot of things that are supposed to help with this issue (including using typeof because I was originally just using <1 or null as my conditional checker and that didn't work either.

Any help would be greatly appreciated.

CodePudding user response:

You can use optional chaining to check if properties of object does exist:

if(obj?.body?.primary?.shares?.shared) {
  ...
}

Check more info here.

  • Related