Tengo una API que solo permite obtener 1000 filas/obtener.
Entonces, por ejemplo, si quiero recuperar todos los datos de la API, la idea es recorrer los datos de respuesta cada vez que los obtenga y verifique su length (si responseData.length ! == 0, luego continúe buscando, deténgase cuando responseData.length === 0, también aumente firstRow cada vez que inicie el nuevo bucle hasta que llegue al final (responseData.length === 0)
const fetchDataByRowCount = async (url, token, rowCount = 2, firstRow = 0) => { // firstRow is the value where the next fetch starts (Eg: 0-999, 1000-1999, etc.). // rowCount is the value for total rows fetched (Eg: 1000 rows for each fetching time). const data = await axios({ method: "get", url: `${url}?rowCount=${rowCount}&firstRow=${firstRow}`, headers: { client_id: "", Authorization: `Bearer ${token}`, }, }); return data.data; }; export const paginatedFetch = async (url, type, rowCount = 2, firstRow = 0) => { let newResponse; let total = []; let token = await getToken(type); // stored to reuse token within an hour do { if (!token) { const newToken = await getToken(type); newResponse = await fetchDataByRowCount(url, newToken); } else { newResponse = await fetchDataByRowCount( url, token, (rowCount = 2), (firstRow = 0) ); } // console.log(total, "total"); total = [...total, ...newResponse]; // newResponse = []; let newFirstRow = firstRow + 1000; newResponse = await fetchDataByRowCount( url, token, (rowCount = 2), newFirstRow ); total = [...total, ...newResponse]; } while (newResponse.length !== 0); return total; }; Pero el problema es que mi función no salió del bucle do while while, newResponse siempre devuelve valor !==0. Además, la función solo se ejecuta una vez.
¿Podrían ayudarme a verificar esto, por favor?
Del código que publicaste, todavía hay algo que no puedo descifrar, y es rowCount , así que lo dejo tal como está en el siguiente código "remasterizado":
export const paginatedFetch = async (url, type, rowCount = 2, firstRow = 0) => { let newResponse; let total = []; let token; let numberOfRows = firstRow; do { if (!token) token = await getToken(type); newResponse = await fetchDataByRowCount( url, token, (rowCount = 2), numberOfRows ); total = [...total, ...newResponse]; numberOfRows += 1000; } while (newResponse.length !== 0); return total; };Me deshice de algunas cosas que eran redundantes e hice que el código fuera un poco más eficiente con asignaciones de variables, etc.
También mencionas esto:
¡newResponse siempre devuelve valor! == 0.
Tenga cuidado al hacer esto, ya que newResponse inicialmente no está undefined . Ahora nunca usé bucles do...while while, así que no sé exactamente qué podría pasar, pero podría, por ejemplo, no ejecutarse en absoluto. Por lo tanto Also, the function only runs once si está hablando de la función paginatedFetch .
Ahora, si tuviera que reescribirlo, lo haría así:
export const paginatedFetch = async (url, type, rowCount = 2, firstRow = 0) => { let total = []; let token; let numberOfRows = firstRow; while (true) { if (!token) token = await getToken(type); let res = await fetchDataByRowCount( url, token, (rowCount = 2), numberOfRows ); total = [...total, ...res]; numberOfRows += 1000; if (res.length <= 0) break; } return total; }; Nuevamente, tenga cuidado con while (true) , debe estar absolutamente seguro de lo que devuelve la API y res es de hecho una array .
La mejor solución sería la API (si usted es el desarrollador) dando un punto final para contar el número total de filas. De esa manera, tendría una manera de estar absolutamente seguro de cuántas filas hay y escribir su código alrededor de eso.