I need a recursive method to roll up all results from a series of paginated calls and returns the complete list of results. Something feels off in the way I am doing it and feel there is a better way to do this, possibly with Array.reduce
Any recommendations appreciated.
interface Result {
users: Widget[];
start: number;
}
interface Widget {
id: number;
}
// create 3 widgets for test
const widgets = Array(3).fill(null).map((i, index: number) => {
return {
id: index + 1,
} as Widget;
});
const getFromAPI = (start: number = 0): Result => {
// return 1 at a time from a specified position
const current = widgets.slice(start, start + 1);
let nextStart: number;
if (start < widgets.length - 1) {
nextStart = start + 1;
}
return {
users: current,
start: nextStart,
}
}
// I don't like that em is outside the scope here
let em: Widget[] = [];
const getWidgets = (start?: number): Widget[] => {
const result = getFromAPI(start);
em = [...em, ...result.users];
if (result.start) {
getWidgets(result.start);
}
return em;
}
const all = getWidgets();