Skip to content

Instantly share code, notes, and snippets.

@rg3915
Last active December 15, 2024 02:41
Show Gist options
  • Save rg3915/483646b99474390c1ab6a6b03bb56251 to your computer and use it in GitHub Desktop.
Save rg3915/483646b99474390c1ab6a6b03bb56251 to your computer and use it in GitHub Desktop.
Recursive load data with AlpineJS
const getItems = () => ({
items: [],
offset: 0,
limit: 10,
loading: false,
hasMore: true,
init() {
this.loadItems();
},
loadItems() {
if (this.loading || !this.hasMore) return;
this.loading = true;
axios.get('/api/v1/persons', {
params: {
offset: this.offset,
limit: this.limit,
},
})
.then((response) => {
const data = response.data;
this.items = this.items.concat(data.items);
this.hasMore = data.has_more;
this.offset += this.limit;
if (this.hasMore) {
// Add a slight delay before the next call
setTimeout(() => this.loadItems(), 500);
}
})
.catch((error) => {
console.error('Error loading items:', error);
this.hasMore = false; // Stop further recursive calls on error
})
.finally(() => {
this.loading = false;
});
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment