Created
November 24, 2019 04:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome, saved so much time for me !