Skip to content

Commit caa1993

Browse files
committed
Refactor usePrefetch
1 parent 943fee5 commit caa1993

File tree

1 file changed

+19
-26
lines changed

1 file changed

+19
-26
lines changed

packages/svelte/src/usePrefetch.ts

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,33 @@
11
import { router, type VisitOptions } from '@inertiajs/core'
22
import { onDestroy, onMount } from 'svelte'
3-
import { writable, type Readable } from 'svelte/store'
3+
import { readonly, writable } from 'svelte/store'
44

5-
interface InertiaPrefetch {
6-
isPrefetched: boolean
7-
isPrefetching: boolean
8-
lastUpdatedAt: number | null
9-
flush: () => void
10-
}
11-
12-
export default function usePrefetch(options: VisitOptions = {}): Readable<InertiaPrefetch> {
13-
const { subscribe, update } = writable<InertiaPrefetch>({
14-
isPrefetched: false,
15-
isPrefetching: false,
16-
lastUpdatedAt: null,
17-
flush() {
18-
router.flush(window.location.pathname, options)
19-
},
20-
})
5+
export default function usePrefetch(options: VisitOptions = {}) {
6+
const isPrefetched = writable(false)
7+
const isPrefetching = writable(false)
8+
const lastUpdatedAt = writable<number | null>(null)
219

2210
const cached = router.getCached(window.location.pathname, options)
2311
const inFlight = router.getPrefetching(window.location.pathname, options)
2412

25-
update((state) => ({
26-
...state,
27-
isPrefetched: cached !== null,
28-
isPrefetching: inFlight !== null,
29-
lastUpdatedAt: cached?.staleTimestamp || null,
30-
}))
13+
isPrefetched.set(cached !== null)
14+
isPrefetching.set(inFlight !== null)
15+
lastUpdatedAt.set(cached?.staleTimestamp || null)
3116

3217
let removePrefetchedListener: () => void
3318
let removePrefetchingListener: () => void
3419

3520
onMount(() => {
3621
removePrefetchingListener = router.on('prefetching', ({ detail }) => {
3722
if (detail.visit.url.pathname === window.location.pathname) {
38-
update((state) => ({ ...state, isPrefetching: true }))
23+
isPrefetching.set(true)
3924
}
4025
})
4126

4227
removePrefetchedListener = router.on('prefetched', ({ detail }) => {
4328
if (detail.visit.url.pathname === window.location.pathname) {
44-
update((state) => ({ ...state, isPrefetched: true, isPrefetching: false }))
29+
isPrefetched.set(true)
30+
isPrefetching.set(false)
4531
}
4632
})
4733
})
@@ -51,5 +37,12 @@ export default function usePrefetch(options: VisitOptions = {}): Readable<Inerti
5137
removePrefetchingListener()
5238
})
5339

54-
return { subscribe }
40+
return {
41+
isPrefetched: readonly(isPrefetched),
42+
isPrefetching: readonly(isPrefetching),
43+
lastUpdatedAt: readonly(lastUpdatedAt),
44+
flush() {
45+
router.flush(window.location.pathname, options)
46+
},
47+
}
5548
}

0 commit comments

Comments
 (0)