How to fetch data over multiple pages?

前端 未结 2 821
时光说笑
时光说笑 2021-01-27 00:50

My project is based on React, redux, redux-saga, es6 and I try to fetch data from this API:

http://api.dhsprogram.com/rest/dhs/data/BD,2000,2004,2007?&returnFields=C

2条回答
  •  情深已故
    2021-01-27 01:35

    Here is another possible solution using async/await. The beauty of this is that the total_pages count is dynamic, so that if it increases while you're processing your request, it'll make sure you get it all.

    async function fetchMetaData() {
      let allData = [];
      let morePagesAvailable = true;
      let currentPage = 0;
    
      while(morePagesAvailable) {
        currentPage++;
        const response = await fetch(`http://api.dhsprogram.com/rest/dhs/data?page=${currentPage}`)
        let { data, total_pages } = await response.json();
        data.forEach(e => allData.unshift(e));
        morePagesAvailable = currentPage < total_pages;
      }
    
      return allData;
    }
    

提交回复
热议问题