Pinia colada query setup
This commit is contained in:
@@ -2,25 +2,29 @@
|
|||||||
import type { ApiResponse } from '@/types/Api'
|
import type { ApiResponse } from '@/types/Api'
|
||||||
import type { BikeParking } from '@/types/Bikes'
|
import type { BikeParking } from '@/types/Bikes'
|
||||||
import { API_BASE_URL, API_LIMIT } from '@/utils/const'
|
import { API_BASE_URL, API_LIMIT } from '@/utils/const'
|
||||||
import { ref } from 'vue'
|
import { useQuery } from '@pinia/colada'
|
||||||
|
|
||||||
|
async function fetchAllBikeParkings(): Promise<BikeParking[]> {
|
||||||
|
const firstPage = await fetch(`${API_BASE_URL}?limit=${API_LIMIT}`).then(r => r.json()) as ApiResponse
|
||||||
|
const { total_count } = firstPage
|
||||||
|
|
||||||
const res = ref<BikeParking[]>([])
|
const remainingPages = await Promise.all(
|
||||||
|
|
||||||
const firstPage = await fetch(`${API_BASE_URL}?limit=${API_LIMIT}`).then(r => r.json()) as ApiResponse
|
|
||||||
const { total_count } = firstPage
|
|
||||||
|
|
||||||
const remainingPages = await Promise.all(
|
|
||||||
Array.from(
|
Array.from(
|
||||||
{ length: Math.ceil((total_count - API_LIMIT) / API_LIMIT) },
|
{ length: Math.ceil((total_count - API_LIMIT) / API_LIMIT) },
|
||||||
(_, i) => fetch(`${API_BASE_URL}?limit=${API_LIMIT}&offset=${(i + 1) * API_LIMIT}`).then(r => r.json()) as Promise<ApiResponse>
|
(_, i) => fetch(`${API_BASE_URL}?limit=${API_LIMIT}&offset=${(i + 1) * API_LIMIT}`).then(r => r.json()) as Promise<ApiResponse>
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
res.value = [
|
return [
|
||||||
...(firstPage.results ?? []),
|
...(firstPage.results ?? []),
|
||||||
...remainingPages.flatMap(page => page.results ?? [])
|
...remainingPages.flatMap(page => page.results ?? [])
|
||||||
]
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
const { state } = useQuery({
|
||||||
|
key: ['bike-parkings'],
|
||||||
|
query: fetchAllBikeParkings,
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -31,8 +35,8 @@ res.value = [
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main class="h-screen w-screen grid place-items-center">
|
<main class="h-screen w-screen grid place-items-center">
|
||||||
<pre>
|
<div v-if="state.status === 'pending'">Loading...</div>
|
||||||
{{ res }}
|
<div v-else-if="state.status === 'error'">Error: {{ state.error.message }}</div>
|
||||||
</pre>
|
<pre v-else>{{ state.data }}</pre>
|
||||||
</main>
|
</main>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
Reference in New Issue
Block a user