Last active
December 15, 2024 02:41
-
-
Save rg3915/483646b99474390c1ab6a6b03bb56251 to your computer and use it in GitHub Desktop.
Recursive load data with AlpineJS
This file contains hidden or 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
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