Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

inject-is-restoring.ts

53 lines2.0 KB

1import {
2 InjectionToken,
3 Injector,
4 assertInInjectionContext,
5 inject,
6 signal,
7} from '@angular/core'
8import type { Provider, Signal } from '@angular/core'
9​
10/**
11 * Internal token used to track isRestoring state, accessible in public API through `injectIsRestoring` and set via `provideIsRestoring`
12 */
13const IS_RESTORING = new InjectionToken('', {
14 // Default value when not provided
15 factory: () => signal(false).asReadonly(),
16})
17​
18interface InjectIsRestoringOptions {
19 /**
20 * The `Injector` to use to get the isRestoring signal.
21 *
22 * If this is not provided, the current injection context will be used instead (via `inject`).
23 */
24 injector?: Injector
26​
27/**
28 * Injects a signal that tracks whether a restore (e.g. from a persisted client, wired up via
29 * `provideIsRestoring`) is currently in progress. `injectQuery` and friends also check this internally to
30 * avoid race conditions between the restore and initializing queries.
31 * @param options - Additional configuration
32 * @returns A readonly `Signal<boolean>` β€” `true` while a restore is in progress, `false` otherwise (the
33 * default when no `provideIsRestoring` provider is registered).
34 */
35export function injectIsRestoring(options?: InjectIsRestoringOptions) {
36 !options?.injector && assertInInjectionContext(injectIsRestoring)
37 const injector = options?.injector ?? inject(Injector)
38 return injector.get(IS_RESTORING)
40​
41/**
42 * Registers a provider for the restore state read by `injectIsRestoring`. Wire this up wherever you drive a
43 * restore yourself β€” e.g. a persist-client integration β€” so `injectQuery` and friends can defer subscribing
44 * to their observer (avoiding a race with the restore) until the restore signal flips back to `false`.
45 * @param isRestoring - A readonly `Signal<boolean>` that tracks the restore state.
46 * @returns A provider for the `isRestoring` signal.
47 */
48export function provideIsRestoring(isRestoring: Signal<boolean>): Provider {
49 return {
50 provide: IS_RESTORING,
51 useValue: isRestoring,
52 }