Home > OS >  Clueless about format of returned json data from fetch
Clueless about format of returned json data from fetch

Time:09-11

This is likely a simple question for many, however I find it extremely confusing. I have a 'double fetch' using a 'Promise.all' as follows:

Promise.all([
fetch('https://jsonplaceholder.typicode.com/posts'),
fetch('https://jsonplaceholder.typicode.com/users')
]).then(function (responses) {
// Get a JSON object from each of the responses
return Promise.all(responses.map(function (response) {
    return response.json();
}));
}).then(function (data) {
// Log the data to the console
// You would do something with both sets of data here
console.log(data);
}).catch(function (error) {
// if there's an error, log it
console.log(error);
});

My question is how to properly read the results from the fetch calls? If you look at the two URLs the data is laid out differently for each. I understand the two fetch calls format the data as "0" (for 'posts') and "1" (for 'users') respectively. At that point I am having greatly difficulty stripping out specific data. For example I have attempted (among other attempts):

console.log(data[1].address[0].street);
console.log(data[1].address.street);    
console.log(data[0].title); 
console.log(data[0].title[3]);

Can anybody please explain how to properly retrieve whatever necessary data I need to have from the 'multiple' fetch calls? I am not able to locate resources on the Internet relating to this topic...likely because I don't exactly know what to search for. I thank you in advance. Any help is greatly appreciated, this is very frustrating.

CodePudding user response:

I think this answer might help you grasp the idea of what is going on with data when you are using Promise.all(), and how to retrieve the object properties, i've added some comments to the code for explanation.

const handlePostsFetch = (posts) => {
  // Do something with your Posts
  console.log(posts);
  // => [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

  const firstPost = posts[0];
  const secondPost = posts[1];
  const thirdPost = posts[2];

  console.log(firstPost.title);
  // => "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"

  console.log(secondPost.body);
  // => est rerum tempore vitae...

  console.log(thirdPost.id);
  // => 3

  const allPostsIds = posts.map((post) => post.id);
  console.log(allPostsIds);
  // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, …]
};

const handleUsersFetch = (users) => {
  // Do something with your users
  console.log(users);
  // => [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

  // Get first user
  console.log(users[0]);
  // => {id: 1, name: "Leanne Graham", username: "Bret", email: "[email protected]", address: Object…}

  // get all user names
  const allUsersNames = users.map(({ name }) => name);
  console.log(allUsersNames);
  // => ["Leanne Graham", "Ervin Howell", "Clementine Bauch", "Patricia Lebsack", "Chelsey Dietrich", "Mrs. Dennis Schulist", "Kurtis Weissnat", "Nicholas Runolfsdottir V", "Glenna Reichert", "Clementina DuBuque"]
};

// We are using async/await syntax to keep it clean and simple
// Promise all .then() passes response array of data (each data is also an array), here we simply destructure response array and await for results
// Then we pass each resolved data to functions
const handleSuccessResponse = async ([posts, users]) => {
  handlePostsFetch(await posts.json());
  handleUsersFetch(await users.json());
};

Promise.all([
  fetch("https://jsonplaceholder.typicode.com/posts"),
  fetch("https://jsonplaceholder.typicode.com/users")
])
  .then(handleSuccessResponse)
  .catch(function (error) {
    // if there's an error, log it
    console.log(error);
  });


Some references:

Destructuring -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Accessing object properties -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Accessing an array items -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#access_an_array_item_by_its_index

CodePudding user response:

Using data[0] for users and data[1] for posts is working fine, that is not where your issue is.

Your specific log statements won't work because both of the responses are lists of objects. You're trying to access properties from the list instead of selecting an object from the list and accessing the properties there.

For example, if you want to get the address for the very first user you need to do something like the following:

console.log(data[1][0].address.street)
  • Related