0

I'm learning Javascript and today I learned AJAX. I am using Vanilla JS and simple AJAX. My task is to get the object of a user from the url by user input - ID. I've tried the .data and still won't work. Any help would be appriciated!

async function display() {
  try {
    let id = +userID.value;
    const url = `https://jsonplaceholder.typicode.com/users/${id}`;
    const response = await fetch(url);
    const rootObject = await response.json();
    const users = rootObject.data;
    getUser(users);
  } catch (err) {
    alert(err.message);
  }
}

display()

I have another function - getusers(users) that currently is empty because it isn't working. How can I access the object only from the url?

3
  • 1
    There is no data property in the (parsed) JSON returned. console.log(rootObject) to see the actual structure of the object. response.data is something you normally see with Axios which isn't what you're using. Commented Jul 9, 2022 at 8:37
  • When I write console.log(rootObject) I get the user by ID. But when I want to display it with getUser function it won't display it Commented Jul 9, 2022 at 8:40
  • We don't know how your getUser function works Commented Jul 9, 2022 at 8:44

1 Answer 1

1

There is no data property in the returned JSON. Just parse the JSON and then have that data as an argument to getUser.

function getUser(data) {
  for (const prop in data) {
    console.log(`${prop}: ${data[prop]}`);
  }
}

async function display(id) {
  try {
    const url = `https://jsonplaceholder.typicode.com/users/${id}`;
    const response = await fetch(url);
    const data = await response.json();
    getUser(data);
  } catch (err) {
    console.log(err.message);
  }
}

display(3);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.