Skip to content

Instantly share code, notes, and snippets.

@DanielCender
Created November 24, 2019 04:40
Show Gist options
  • Save DanielCender/417a861ee5c0bb3d9131c79e99fbb184 to your computer and use it in GitHub Desktop.
Save DanielCender/417a861ee5c0bb3d9131c79e99fbb184 to your computer and use it in GitHub Desktop.
A recursive function utilizing the AWS-Amplify library for web fetches in React apps
import { API, graphqlOperation } from 'aws-amplify';
/**
* @desc Recursively fetch all items in a list query using nextToken
* @param {Object} query The query object from cda-graphql in use.
* @param {Object} variables The variables to pass to query.
* @param {Array} items Any preliminary Items already fetched
* @param {Function} callback Optional callback function to be fired with every batch of items from query iteration.
* @returns {Array} Array of all items received from queries.
*/
async function fetchItemsNextToken({ query, variables, items = [], callback = undefined }) {
const { data } = await API.graphql(graphqlOperation(query, variables));
const key = Object.keys(data).find(k => k.includes('list'));
const res = data[key]; // res = { items: [], nextToken: '' }
items.push(...res.items);
if (callback) {
callback(res.items);
}
if (!res.nextToken) return items;
// eslint-disable-next-line no-param-reassign
variables.nextToken = res.nextToken;
return fetchItemsNextToken({ query, variables, items, callback });
}
export default fetchItemsNextToken;
@siddharatha
Copy link

Awesome, saved so much time for me !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment