Skip to content

Commit

Permalink
Add useIsDataLoading hook
Browse files Browse the repository at this point in the history
  • Loading branch information
nemanjamalesija committed Jan 2, 2025
1 parent 643632b commit c399e36
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
1 change: 1 addition & 0 deletions client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ declare module 'vue-router/auto' {
export {
DataLoaderPlugin,
NavigationResult,
useIsDataLoading
} from 'unplugin-vue-router/data-loaders'
// must be added to the virtual vue-router/auto
// FIXME: is there a way to achieve this without losing the types?
Expand Down
6 changes: 5 additions & 1 deletion src/data-loaders/entries/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ export type {
export { toLazyValue } from '../createDataLoader'

// new data fetching
export { DataLoaderPlugin, NavigationResult } from '../navigation-guard'
export {
DataLoaderPlugin,
NavigationResult,
useIsDataLoading,
} from '../navigation-guard'
export type {
DataLoaderPluginOptions,
SetupLoaderGuardOptions,
Expand Down
33 changes: 33 additions & 0 deletions src/data-loaders/navigation-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type {
} from 'vue-router'
import { type _Awaitable } from '../utils'
import { toLazyValue, type UseDataLoader } from './createDataLoader'
import { shallowRef, watch } from 'vue'

/**
* TODO: export functions that allow preloading outside of a navigation guard
Expand Down Expand Up @@ -414,3 +415,35 @@ export interface DataLoaderPluginOptions {
*/
errors?: Array<new (...args: any) => any> | ((reason?: unknown) => boolean)
}

export function useIsDataLoading(router: Router) {
const isLoading = shallowRef(false)

watch(
() => {
// read the current route
const currentRoute = router.currentRoute.value
if (!currentRoute) {
return []
}

// extract the loaders from route meta
const loaders = currentRoute.meta[LOADER_SET_KEY] || new Set()

// map each loader to its isLoading.value
return Array.from(loaders).map((loader) => {
const entry = loader._.getEntry(router)
return entry?.isLoading.value ?? false
})
},
(loaderStates) => {
// if any loader is true, isLoading becomes true
isLoading.value = loaderStates.some((state) => state)
},
{
immediate: true,
}
)

return isLoading
}

0 comments on commit c399e36

Please sign in to comment.