Marco
Marco

Reputation: 63

Trying to retrieve json informations in a function with Fetch API and then trying to use them in another function

I need to fetch some informations from a URL (which contains informations in JSON) about several objects. So i wrote:

static fetchObj(){
fetch("http://localhost:1337/objects")
.then(callback => { 
return callback.json();
})
.then(data => {
console.log(data);
});
}

Here I can retrieve the things I need and console them for being sure.

Then I have to use these data in another function that finds these objects by ID:

static fetchObjById(id) {
      MyClass.fetchObj()
      .then(
          for(var i=0; i<data.id.length; i++){
            if(data[i].id == id)
              console.log("found");
            else
              console.log("not found");
          }
   }

But it doesn't work at all.. I tried several methods but nothing.. I hope someone can help me :)

Upvotes: 0

Views: 65

Answers (2)

topic
topic

Reputation: 372

then() expects a function. You can access the Promise's result data through this function's single parameter, which is easily accomplished with an arrow function.

Also, I would recommend you to ditch the explicit for loop and look into declarative programming. Similarly to then(), calling forEach() on an array gives you access to each element with an arrow function. To me, this is much more readable.

Finally, the console.log call could be simplified a little by first declaring what the print message should be (using a ternary operator), then calling console.log once with that message.

const fetchObjById = (id) => {
  MyClass.fetchObj()
    .then(data => {
        data.forEach(d => {
          const message = d.id === id
            ? 'found'
            : 'not found';
          console.log(message);
        })
      }
}

Upvotes: 1

Sanjeet kumar
Sanjeet kumar

Reputation: 3441

This is also a way to find the id.

var id = 4;
function fetchObjById(data) {
    console.log(data);
    for(var i = 0; i < data.length; i++){
        if(data[i].id === id) {
            console.log('found');
            break;
        }
    }
}

var myData;
fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(data => myData = data)
  .then(() => fetchObjById(myData));

Upvotes: 1

Related Questions