We've had a lot of customers ask how to return all the responses for a cursor-based paginated API, where:
- You make a request to an API
- API returns the first
n
results and acursor
cursor
is used in a subsequent request to fetch the nextn
results
If you want to fetch all the results, create two queries. The first will be your API Query to fetch your results. The second is is a JavaScript Query, which calls the API Query as many times as we need to. In this case, we're using offset
as our cursor.
Note that offset
is undefined-- that's okay. We'll be using the JS Query to inject the value through additionalScope
(more info here).
Now, we want to have a JS Query, like so: Recursive Fetch - Replit
// Airtable uses cursor-based pagination. This function recursively calls the API as long as the cursor from the previous request exists.
const fetchAll = (offset, records) => {
// Base case: we've reached the end, and there are no more cursors.
if (offset == null) return records
// Wrap the query result in a promise
return new Promise(resolve => {
return apiQuery.trigger({
additionalScope: {
offset
},
onSuccess: queryResult => {
// Add the records from this query to all the records we have so far
const newResults = records.concat(queryResult.records)
return resolve(fetchAll(queryResult.offset, newResults))
}
})
})
}
return fetchAll(0, [])
This query recursively calls the API Query as many times as we have offset
returned to us (i.e., until we've returned all the data.)