Skip to content

Commit ee3cf31

Browse files
authored
feat(data-loaders)!: define colada loaders with query options (#2973)
BREAKING CHANGE: `defineColadaLoader()` now takes a function that returns Pinia Colada query options. Loader options (`lazy`, `server`, `errors`) move to the last argument. The `signal` passed to `query` is now the one from Pinia Colada. The navigation signal is in the second argument of the function. ```ts // before defineColadaLoader('/users/[id]', { key: to => ['users', to.params.id], query: (to, { signal }) => getUser(to.params.id, { signal }), staleTime: 10_000, lazy: true, }) // after defineColadaLoader( '/users/[id]', to => ({ key: ['users', to.params.id], query: ({ signal }) => getUser(to.params.id, { signal }), staleTime: 10_000, }), { lazy: true } ) ```
1 parent c02b98a commit ee3cf31

7 files changed

Lines changed: 272 additions & 231 deletions

File tree

‎packages/docs/data-loaders/colada/index.md‎

Lines changed: 53 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
Loaders that use [@pinia/colada](https://github.com/posva/pinia-colada) under the hood. These loaders provide the most efficient solution to asynchronous state with cache, ssr support and more.
44

5-
The key used in these loaders is directly passed to `useQuery()` from `@pinia/colada` and can be invalidated with `useMutation()` hooks. See [Pinia Colada documentation about query invalidation](https://pinia-colada.esm.dev/guide/query-invalidation.html) to learn more.
5+
A Pinia Colada loader is a `useQuery()` bound to the route: you give it a function that receives the route and returns [query options](https://pinia-colada.esm.dev/guide/queries.html). The key is directly passed to `useQuery()` from `@pinia/colada` and can be invalidated with `useMutation()` hooks. See [Pinia Colada documentation about query invalidation](https://pinia-colada.esm.dev/guide/query-invalidation.html) to learn more.
66

77
## Setup
88

@@ -23,14 +23,12 @@ import './typed-router.d'
2323
import { defineColadaLoader } from 'vue-router/experimental/pinia-colada'
2424
import { getUserById } from '../api'
2525
26-
export const useUserData = defineColadaLoader({
27-
async query(to, { signal }) {
28-
return getUserById(to.params.id, { signal })
29-
},
30-
key: to => ['users', to.params.id],
26+
export const useUserData = defineColadaLoader('/users/[id]', to => ({
27+
key: ['users', to.params.id],
28+
query: ({ signal }) => getUserById(to.params.id, { signal }),
3129
// Keep the data "fresh" 10 seconds to avoid fetching the same data too often
3230
staleTime: 10000,
33-
})
31+
}))
3432
</script>
3533
3634
<script lang="ts" setup>
@@ -82,14 +80,57 @@ const {
8280
<!-- TODO: add autocompletion to show all pinia colada options -->
8381

8482
::: tip
85-
You can pass a route name to `defineColadaLoader` to get typed routes in the `query` function.
83+
The route name is optional. It gives a typed `to` parameter.
84+
:::
85+
86+
## Reusing query options
87+
88+
Because the loader returns query options, you can reuse the ones defined with [`defineQueryOptions()`](https://pinia-colada.esm.dev/guide/reusable-queries.html):
89+
90+
```ts
91+
import { defineQueryOptions } from '@pinia/colada'
92+
import { defineColadaLoader } from 'vue-router/experimental/pinia-colada'
93+
94+
const userQuery = defineQueryOptions((id: string) => ({
95+
key: ['users', id],
96+
query: () => getUserById(id),
97+
}))
98+
99+
export const useUserData = defineColadaLoader('/users/[id]', to =>
100+
userQuery(to.params.id)
101+
)
102+
```
103+
104+
## Loader options
105+
106+
Data loader options like `lazy`, `server` or `errors` go in the last argument. They are not query options:
107+
108+
```ts
109+
export const useUserData = defineColadaLoader(
110+
'/users/[id]',
111+
to => userQuery(to.params.id),
112+
{ lazy: true }
113+
)
114+
```
115+
116+
## Abort signals
117+
118+
The `query` function receives the `signal` of Pinia Colada. Like with `useQuery()`, Pinia Colada aborts it when no component uses the query anymore, e.g. when a cancelled navigation makes the page show the previous query again.
119+
120+
The function that returns the query options receives the navigation context as its second argument. Its `signal` is aborted when the navigation is cancelled. Use it only if the request must stop with the navigation:
86121

87122
```ts
88-
export const useUserData = defineColadaLoader('/users/[id]', {
89-
// ...
90-
})
123+
export const useUserData = defineColadaLoader(
124+
'/users/[id]',
125+
(to, navigation) => ({
126+
key: ['users', to.params.id],
127+
query: () => getUserById(to.params.id, { signal: navigation.signal }),
128+
})
129+
)
91130
```
92131

132+
::: warning
133+
The function that returns the query options can run more than once for the same route. Do not cause side effects in it.
93134
:::
94135

95136
## Refresh by default
@@ -98,7 +139,7 @@ To avoid unnecessary frequent refreshes, Pinia Colada refreshes the data when na
98139

99140
## Route tracking
100141

101-
The `query` function tracks what is used in the `to` parameter and will only refresh the data if **tracked** properties change. This means that if you use `to.params.id` in the `query` function, it will only refetch the data if the `id` parameter changes but not if other properties like `to.query`, `to.hash` or even `to.params.other` change. To make sure the data is updated, it will still refresh in these scenarios. Configure the `staleTime` option to control how often the data should be refreshed.
142+
The loader tracks what is used in the `to` parameter, in the function that returns the query options and in the `query` function. It only refreshes the data if **tracked** properties change. This means that if you use `to.params.id`, it will only refetch the data if the `id` parameter changes but not if other properties like `to.query`, `to.hash` or even `to.params.other` change. To make sure the data is updated, it will still refresh in these scenarios. Configure the `staleTime` option to control how often the data should be refreshed.
102143

103144
## SSR
104145

‎packages/docs/data-loaders/defining-loaders.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Defining Data Loaders
22

3-
In order to use data loaders, you need to define them first. Data loaders themselves are the composables returned by the different `defineLoader` functions. Each loader definition is specific to the `defineLoader` function used. For example, `defineBasicLoader` expects an async function as the first argument while `defineColadaLoader` expects an object with a `query` function. All loaders should allow to pass an async function that can throw errors, and call `reroute()` to control the navigation.
3+
In order to use data loaders, you need to define them first. Data loaders themselves are the composables returned by the different `defineLoader` functions. Each loader definition is specific to the `defineLoader` function used. For example, `defineBasicLoader` expects an async function as the first argument while `defineColadaLoader` expects a function that returns Pinia Colada query options. All loaders should allow to pass an async function that can throw errors, and call `reroute()` to control the navigation.
44

55
Any composables returned by _any_ `defineLoader` function share the same signature:
66

‎packages/router/src/experimental/data-loaders/createDataLoader.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,8 @@ export function createDataLoader<
121121
setCurrentContext([entry, router, to])
122122
entry.pendingTo = to
123123

124+
// sync throws (e.g. in colada query options) are user bugs: they are not
125+
// caught so they stay visible
124126
const initialData = initial(entry, to, router)
125127
if (initialData !== undefined) {
126128
entry.data.value = initialData
@@ -153,7 +155,7 @@ export function createDataLoader<
153155
}
154156
}
155157

156-
// loaders are async: they cannot throw synchronously
158+
// loaders are async: a sync throw is a user bug, see initial
157159
running++
158160
const result = fetch(entry, to, router, reload)
159161
running--

‎packages/router/src/experimental/data-loaders/defineColadaLoader.spec.ts‎

Lines changed: 88 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,13 @@ describe(
3232

3333
testDefineLoader(
3434
({ fn, key, ...options }) =>
35-
defineColadaLoader({ ...options, query: fn, key: () => [key ?? 'id'] }),
35+
defineColadaLoader(
36+
(to, context) => ({
37+
key: [key ?? 'id'],
38+
query: () => fn(to, context),
39+
}),
40+
options
41+
),
3642
{
3743
beforeEach() {
3844
const pinia = createPinia()
@@ -115,10 +121,10 @@ describe(
115121

116122
it('avoids refetching fresh data when navigating', async () => {
117123
const query = vi.fn().mockResolvedValue('data')
118-
const useData = defineColadaLoader({
119-
query,
120-
key: to => [to.query.q as string],
121-
})
124+
const useData = defineColadaLoader(to => ({
125+
key: [to.query.q as string],
126+
query: () => query(to),
127+
}))
122128

123129
const { router } = singleLoaderOneRoute(useData)
124130

@@ -138,19 +144,19 @@ describe(
138144

139145
it('avoids refetching fresh nested data when the parent reruns', async () => {
140146
const nestedQuery = vi.fn().mockResolvedValue('nested')
141-
const useNested = defineColadaLoader({
142-
query: nestedQuery,
143-
key: to => ['nested', to.query.q as string],
144-
})
147+
const useNested = defineColadaLoader(to => ({
148+
key: ['nested', to.query.q as string],
149+
query: () => nestedQuery(to),
150+
}))
145151
const parentQuery = vi.fn(async (to: RouteLocationNormalizedLoaded) => {
146152
await useNested()
147153
return to.query.v
148154
})
149155
const { router } = singleLoaderOneRoute(
150-
defineColadaLoader({
151-
query: parentQuery,
152-
key: to => ['parent', to.query.v as string],
153-
})
156+
defineColadaLoader(to => ({
157+
key: ['parent', to.query.v as string],
158+
query: () => parentQuery(to),
159+
}))
154160
)
155161

156162
await router.push('/fetch?q=1&v=1')
@@ -167,7 +173,10 @@ describe(
167173
return `${k}:${to.query.x}`
168174
})
169175
const { router, useData } = singleLoaderOneRoute(
170-
defineColadaLoader({ query, key: to => [to.query.k as string] })
176+
defineColadaLoader(to => ({
177+
key: [to.query.k as string],
178+
query: () => query(to),
179+
}))
171180
)
172181

173182
await router.push('/fetch?k=a&x=1')
@@ -189,10 +198,7 @@ describe(
189198
const query = vi.fn(async () => 'data')
190199

191200
const { router, useData } = singleLoaderOneRoute(
192-
defineColadaLoader({
193-
query,
194-
key: () => ['id'],
195-
})
201+
defineColadaLoader(to => ({ key: ['id'], query }))
196202
)
197203

198204
await router.push('/fetch?v=1')
@@ -225,10 +231,7 @@ describe(
225231
)
226232

227233
const { router, useData } = singleLoaderOneRoute(
228-
defineColadaLoader({
229-
query,
230-
key: () => ['id'],
231-
})
234+
defineColadaLoader(to => ({ key: ['id'], query: () => query(to) }))
232235
)
233236

234237
await router.push('/fetch?v=1')
@@ -245,13 +248,38 @@ describe(
245248
expect(loaderData.value).toBe('1')
246249
})
247250

251+
it('does not store the abort of a cancelled navigation in the cache', async () => {
252+
const { router, app } = singleLoaderOneRoute(
253+
defineColadaLoader(to => ({
254+
key: ['id', to.query.v as string],
255+
query: ({ signal }) =>
256+
to.query.v !== '2'
257+
? Promise.resolve(to.query.v)
258+
: new Promise((_, reject) => {
259+
signal.addEventListener('abort', () => reject(signal.reason))
260+
}),
261+
}))
262+
)
263+
264+
await router.push('/fetch?v=1')
265+
// a new navigation cancels this one while its query is pending
266+
router.push('/fetch?v=2')
267+
await vi.advanceTimersByTimeAsync(0)
268+
await router.push('/fetch?v=3')
269+
await vi.advanceTimersByTimeAsync(0)
270+
271+
const entry = app.runWithContext(() => useQueryCache().get(['id', '2']))
272+
expect(entry).toBeDefined()
273+
expect(entry!.state.value.error).toBe(null)
274+
})
275+
248276
it('hydrates without calling the query on the initial navigation', async () => {
249277
// setups the loader
250278
const query = vi.fn().mockResolvedValue('data')
251-
const useData = defineColadaLoader({
252-
query,
253-
key: () => ['id'],
254-
})
279+
const useData = defineColadaLoader(to => ({
280+
key: ['id'],
281+
query: () => query(to),
282+
}))
255283

256284
// sets up the page
257285
let useDataResult: ReturnType<typeof useData> | undefined
@@ -307,10 +335,10 @@ describe(
307335
it('restores the context after using a loader', async () => {
308336
const query = vi.fn().mockResolvedValue('data')
309337

310-
const useData = defineColadaLoader({
311-
query,
312-
key: () => ['id'],
313-
})
338+
const useData = defineColadaLoader(to => ({
339+
key: ['id'],
340+
query: () => query(to),
341+
}))
314342

315343
let useDataResult: ReturnType<typeof useData> | undefined
316344
const component = defineComponent({
@@ -361,14 +389,14 @@ describe(
361389

362390
it('can refetch nested loaders on invalidation', async () => {
363391
const nestedQuery = vi.fn(async () => [{ id: 0 }, { id: 1 }])
364-
const useListData = defineColadaLoader({
392+
const useListData = defineColadaLoader(() => ({
393+
key: ['items'],
365394
query: nestedQuery,
366-
key: () => ['items'],
367-
})
395+
}))
368396

369-
const useDetailData = defineColadaLoader({
370-
key: to => ['items', { id: to.params.id as string }],
371-
async query(to) {
397+
const useDetailData = defineColadaLoader(to => ({
398+
key: ['items', { id: to.params.id as string }],
399+
async query() {
372400
const list = await useListData()
373401
const item = list.find(
374402
item => String(item.id) === (to.params.id as string)
@@ -378,7 +406,7 @@ describe(
378406
}
379407
return { ...item, when: Date.now() }
380408
},
381-
})
409+
}))
382410

383411
const component = defineComponent({
384412
setup() {
@@ -419,15 +447,15 @@ describe(
419447

420448
it('marks loader queries as inactive when navigating away from the page', async () => {
421449
// Create two loaders with different keys
422-
const useLoader1 = defineColadaLoader({
423-
query: async () => 'data-1',
450+
const useLoader1 = defineColadaLoader(() => ({
424451
key: ['page-1'],
425-
})
452+
query: async () => 'data-1',
453+
}))
426454

427-
const useLoader2 = defineColadaLoader({
428-
query: async () => 'data-2',
455+
const useLoader2 = defineColadaLoader(() => ({
429456
key: ['page-2'],
430-
})
457+
query: async () => 'data-2',
458+
}))
431459

432460
// Create components for each page
433461
const page1 = defineComponent({
@@ -498,10 +526,10 @@ describe(
498526
})
499527

500528
it('marks loader queries as inactive when navigating between pages with different parameters', async () => {
501-
const useLoaderWithParam = defineColadaLoader({
502-
query: async to => `data-${to.params.id as string}`,
503-
key: to => ['page-loader', to.params.id as string],
504-
})
529+
const useLoaderWithParam = defineColadaLoader(to => ({
530+
key: ['page-loader', to.params.id as string],
531+
query: async () => `data-${to.params.id as string}`,
532+
}))
505533

506534
const router = getRouter()
507535
router.addRoute({
@@ -556,12 +584,14 @@ describe(
556584
it('keeps the data of the current route when a lazy navigation is cancelled', async () => {
557585
const bPending = Promise.withResolvers<string>()
558586
// ignores the abort signal
559-
const useItem = defineColadaLoader({
560-
lazy: true,
561-
query: async to =>
562-
to.params.id === 'b' ? bPending.promise : `item-${to.params.id}`,
563-
key: to => ['item', to.params.id as string],
564-
})
587+
const useItem = defineColadaLoader(
588+
to => ({
589+
key: ['item', to.params.id as string],
590+
query: async () =>
591+
to.params.id === 'b' ? bPending.promise : `item-${to.params.id}`,
592+
}),
593+
{ lazy: true }
594+
)
565595

566596
const router = getRouter()
567597
router.addRoute({
@@ -603,16 +633,16 @@ describe(
603633

604634
it('syncs external changes after a loader redirects to the current location', async () => {
605635
const { router, useData, app } = singleLoaderOneRoute(
606-
defineColadaLoader({ query: async () => 'data', key: () => ['id'] })
636+
defineColadaLoader(() => ({ key: ['id'], query: async () => 'data' }))
607637
)
608638
router.addRoute({
609639
path: '/redirect',
610640
meta: {
611641
loaders: [
612-
defineColadaLoader({
642+
defineColadaLoader(() => ({
643+
key: ['redirect'],
613644
query: async () => reroute('/fetch'),
614-
key: () => ['redirect'],
615-
}),
645+
})),
616646
],
617647
},
618648
component: defineComponent({ template: 'redirect' }),
@@ -632,7 +662,7 @@ describe(
632662
v8.setFlagsFromString('--expose-gc')
633663
const gc = runInNewContext('gc') as () => void
634664
const { router } = singleLoaderOneRoute(
635-
defineColadaLoader({ query: async () => 'data', key: () => ['id'] })
665+
defineColadaLoader(() => ({ key: ['id'], query: async () => 'data' }))
636666
)
637667

638668
await router.push('/fetch?v=0')

0 commit comments

Comments
 (0)