简体   繁体   中英

fetch data from api by different ids in reactjs

I have a list of IDs ie: [3,6,7] I want to fetch all objects from api which have 3,6 and 7 as id. I can fetch it with only one ID. like this:

 const response = await fetch(`http://localhost:3000/api`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
    body: JSON.stringify({
      id: 7,
    }),
  });

How can I fetch with different ids? thanks in advance.

You can use Promise.all https://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

const promises = [3,6,7].map(id => {
  return fetch(`http://localhost:3000/api`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
    body: JSON.stringify({
      id,
    }),
  })
})

const response = await Promise.all(promies)
console.log(responese)

fetch(...) returns a promise.

await fetch(...) Gets the result of that returned promise.

So to do more than one call at once you need to handle multiple promises.

const p1 = fetch(...)
const p2 = fetch(...)
const p3 = fetch(...)

const [p1Result, p2Result, p3Result] = await Promise.all(p1, p2, p3);

Will put the results of those fetchers in the Result consts.

It is best to put you're requests in an Array and wait for them to finish.

const myLogic = () => {
    //Put ids in function and get responses
    getByIds([3,6,7]).then(responses => {
        console.log(responses);        
    });
}

const getByIds = async (ids) => {
    //put all promises in an Array so we can let them run and be awaited
    //await is bad practise in loops and usually does not work
    let requests = [];
    let responses = [];

    for (let id in ids)
        requests.push(fetch(`http://localhost:3000/api`, {
            method: 'POST',
            body: JSON.stringify({ id }),
            headers: { 'Content-Type': 'application/json; charset=utf-8' },
        })
            //Add response to array
            .then(response => responses.push(response))
            .catch(err => console.log(err)));

    //Await all requests
    await Promise.all(requests);

    //return all responses
    return responses;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM