Jump to content

Javascript Help - University student

JopemartHD

Hello guys,

 

i'm new to JS and API requests with JSON, i have this Code:
 

function GetUser(UserID) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://reqres.in/api/users/2" , true);
    xhr.onload = function () {
        if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
            alert(xhr.responseText);
            var UserLists = JSON.parse(xhr.responseText);
            return UserLists;
        } else {
            alert("Error " + xhr.status);
        }
    };
    xhr.send();
}

and this is what i'm getting from the API:
image.png.29586e9ca4b5d351c213b9bff4ac971d.png

and i can't find a way of getting the values of "data".

can someone help please? the test API i'm using is :https://reqres.in and for the first request ( /api/users?page=2) i was able to get it but now i cant seem to find a way.

 

Thank you for the help,

João

 

Link to comment
Share on other sites

Link to post
Share on other sites

You json parse the data into

UserLists

So you can get the data with UserLists.data

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, vorticalbox said:

You json parse the data into


UserLists

So you can get the data with UserLists.data

 

i'm getting this error: image.png.8a514165fd38fde11d385825c1edc4c0.png

 

i did this: 

var UserData = GetUser(UserID);
    console.log(UserData.data.last_name);
Link to comment
Share on other sites

Link to post
Share on other sites

Stuff like this is where Javascript gets kinda weird.

 

Basically, when you have

return UserLists;

it's actually returning to the function defined in 

xhr.onload

instead of

GetUser

JavaScript is also an asynchronous language, so you can't necessarily just print the output of a GET request like you would in other languages, such as Python (learn more here: https://www.freecodecamp.org/news/javascript-callback-functions-what-are-callbacks-in-js-and-how-to-use-them/). 

 

There are two ways to solve this: callbacks and promises

Callback:

function GetUser(UserID, cb) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://reqres.in/api/users/2" , true);
    xhr.onload = function () {
      if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
        alert(xhr.responseText);
        var UserLists = JSON.parse(xhr.responseText);
        cb(UserLists);
      } else {
        alert("Error " + xhr.status);
      }
    };
    xhr.send();
}

and then:

GetUser(ID, (UserLists) => {
  console.log(UserLists);
});

 

Promise:

function GetUser(UserID) {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://reqres.in/api/users/2" , true);
    xhr.onload = function () {
      if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
        alert(xhr.responseText);
        var UserLists = JSON.parse(xhr.responseText);
        resolve(UserLists);
      } else {
        alert("Error " + xhr.status);
        reject(xhr.status);
      }
    };
    xhr.send();
  });
}

and then:

GetUsers(ID).then((UserLists) => { console.log(UserLists); });

or (probably the most preferred way, but requires the function to be marked as async):

async function main() {
    var UserData = await GetUser(ID);
    console.log(UserData);
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

omg, i got it with the promise, i also had to add 

UserData['data'].id to be able to get the specific data from it, thank you so much!!!
 
Link to comment
Share on other sites

Link to post
Share on other sites

can you just explain what is the resolve on the GetUser Function? 

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, JopemartHD said:

can you just explain what is the resolve on the GetUser Function? 

Resolve means the promise completed successfully and will pass the parameter (in this case, UserLists) to the .then() function or return UserLists if await was specified.

There's also the reject function, which means the promise ran into an error. You can handle a promise error with a try/catch block (if you're using async/await) or add .catch((e) => { console.error(e); }); to the end of the function call (if you're using .then()).

Link to comment
Share on other sites

Link to post
Share on other sites

as you're in a browser i like the fetch API is much nicer to use

 

const request = await fetch('https://reqres.in/api/users/2')
const { ad, data } = await request.json();

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×