1
1
import { router , type VisitOptions } from '@inertiajs/core'
2
2
import { onDestroy , onMount } from 'svelte'
3
- import { writable , type Readable } from 'svelte/store'
3
+ import { readonly , writable } from 'svelte/store'
4
4
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 )
21
9
22
10
const cached = router . getCached ( window . location . pathname , options )
23
11
const inFlight = router . getPrefetching ( window . location . pathname , options )
24
12
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 )
31
16
32
17
let removePrefetchedListener : ( ) => void
33
18
let removePrefetchingListener : ( ) => void
34
19
35
20
onMount ( ( ) => {
36
21
removePrefetchingListener = router . on ( 'prefetching' , ( { detail } ) => {
37
22
if ( detail . visit . url . pathname === window . location . pathname ) {
38
- update ( ( state ) => ( { ... state , isPrefetching : true } ) )
23
+ isPrefetching . set ( true )
39
24
}
40
25
} )
41
26
42
27
removePrefetchedListener = router . on ( 'prefetched' , ( { detail } ) => {
43
28
if ( detail . visit . url . pathname === window . location . pathname ) {
44
- update ( ( state ) => ( { ...state , isPrefetched : true , isPrefetching : false } ) )
29
+ isPrefetched . set ( true )
30
+ isPrefetching . set ( false )
45
31
}
46
32
} )
47
33
} )
@@ -51,5 +37,12 @@ export default function usePrefetch(options: VisitOptions = {}): Readable<Inerti
51
37
removePrefetchingListener ( )
52
38
} )
53
39
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
+ }
55
48
}
0 commit comments