feat: add error handling for link loading

Improves reliability of link loading functionality:
- Adds error state and handling for failed API requests
- Implements retry mechanism with user-facing error message
- Prevents infinite loading when errors occur
- Defers search API call to mounted hook

These changes enhance user experience by providing clear feedback and recovery options when link loading fails.
This commit is contained in:
ccbikai 2024-12-24 12:43:19 +08:00
parent d6ce2730c9
commit 651dcabdb1
2 changed files with 42 additions and 11 deletions

View file

@ -6,23 +6,37 @@ const links = ref([])
const limit = 24 const limit = 24
let cursor = '' let cursor = ''
let listComplete = false let listComplete = false
let listError = false
async function getLinks() { async function getLinks() {
const data = await useAPI('/api/link/list', { try {
query: { const data = await useAPI('/api/link/list', {
limit, query: {
cursor, limit,
}, cursor,
}) },
links.value = links.value.concat(data.links).filter(Boolean) // Sometimes cloudflare will return null, filter out })
cursor = data.cursor links.value = links.value.concat(data.links).filter(Boolean) // Sometimes cloudflare will return null, filter out
listComplete = data.list_complete cursor = data.cursor
listComplete = data.list_complete
listError = false
}
catch (error) {
console.error(error)
listError = true
}
} }
const { isLoading } = useInfiniteScroll( const { isLoading } = useInfiniteScroll(
document, document,
getLinks, getLinks,
{ distance: 150, interval: 1000, canLoadMore: () => !listComplete }, {
distance: 150,
interval: 1000,
canLoadMore: () => {
return !listError && !listComplete
},
},
) )
function updateLinkList(link, type) { function updateLinkList(link, type) {
@ -68,5 +82,14 @@ function updateLinkList(link, type) {
> >
No more No more
</div> </div>
<div
v-if="listError"
class="flex items-center justify-center text-sm"
>
Loading links failed,
<Button variant="link" @click="getLinks">
Try again
</Button>
</div>
</main> </main>
</template> </template>

View file

@ -8,7 +8,7 @@ const isOpen = ref(false)
const searchTerm = ref('') const searchTerm = ref('')
const selectedLink = ref(null) const selectedLink = ref(null)
const links = await useAPI('/api/link/search') const links = ref([])
const { results: filteredLinks } = useFuse(searchTerm, links, { const { results: filteredLinks } = useFuse(searchTerm, links, {
fuseOptions: { fuseOptions: {
@ -37,6 +37,14 @@ function selectLink(link) {
query: { slug: link.slug }, query: { slug: link.slug },
}) })
} }
async function getLinks() {
links.value = await useAPI('/api/link/search')
}
onMounted(() => {
getLinks()
})
</script> </script>
<template> <template>