feat: add api.refetch method that force reload a view and its data queries

This commit is contained in:
axolotle 2024-08-11 17:48:05 +02:00
parent e0816d14e1
commit 5b5cac5478
3 changed files with 17 additions and 9 deletions

View file

@ -166,7 +166,7 @@ export default {
*/
async fetchAll<T extends any[] = any[]>(
queries: APIQuery[],
{ showModal = false, initial = false } = {},
{ showModal = false, initial = true } = {},
): Promise<T> {
const results = []
for (const query of queries) {
@ -228,6 +228,13 @@ export default {
return this.fetch({ ...query, method: 'DELETE' })
},
refetch() {
// To force a view to reload and refetch initial data, we simply fake update
// the router key
const { updateRouterKey } = useInfos()
updateRouterKey()
},
/**
* Api reconnection helper. Resolve when server is reachable or fail after n attemps
*

View file

@ -8,9 +8,9 @@ import type {
import { useRouter } from 'vue-router'
import api from '@/api'
import { isEmptyValue, timeout } from '@/helpers/commons'
import { timeout } from '@/helpers/commons'
import i18n from '@/i18n'
import type { CustomRoute, RouteFromTo } from '@/types/commons'
import type { CustomRoute } from '@/types/commons'
import { useDomains } from './data'
import { useRequests, type ReconnectingArgs } from './useRequests'
@ -105,9 +105,10 @@ export const useInfos = createGlobalState(() => {
useRequests().reconnecting.value = args
}
function updateRouterKey({ to }: RouteFromTo) {
if (isEmptyValue(to.params)) {
routerKey.value = undefined
function updateRouterKey(to?: RouteLocationNormalized) {
if (!to) {
// Trick to force a view reload
routerKey.value += '0'
return
}
// If the next route uses the same component as the previous one, Vue will not
@ -119,11 +120,10 @@ export const useInfos = createGlobalState(() => {
const params = to.meta.routerParams
? to.meta.routerParams.map((key) => to.params[key])
: Object.values(to.params)
routerKey.value = `${to.name?.toString()}-${params.join('-')}`
}
function updateBreadcrumb({ to }: RouteFromTo) {
function updateBreadcrumb(to: RouteLocationNormalized) {
function getRouteNames(route: RouteLocationNormalized): string[] {
if (route.meta.breadcrumb) return route.meta.breadcrumb
const parentRoute = route.matched

View file

@ -1,5 +1,5 @@
import type { Breakpoint } from 'bootstrap-vue-next'
import type { RouteLocationNamedRaw } from 'vue-router'
import type { RouteLocationNamedRaw, RouteLocationNormalized } from 'vue-router'
export type Obj<T = any> = Record<string, T>
@ -24,6 +24,7 @@ export type CustomRoute = {
text: string
icon?: string
}
export type RouteFromTo = Record<'to' | 'from', RouteLocationNormalized>
export type Translation = string | Record<string, string>
export type StateVariant = 'success' | 'info' | 'warning' | 'danger'