@navios/di-react 0.9.0 → 2.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/README.md +45 -665
- package/lib/{index.js → index.cjs} +249 -258
- package/lib/index.cjs.map +1 -0
- package/lib/{index.d.ts → index.d.cts} +94 -123
- package/lib/index.d.cts.map +1 -0
- package/lib/index.d.mts +93 -122
- package/lib/index.d.mts.map +1 -1
- package/lib/index.mjs +248 -258
- package/lib/index.mjs.map +1 -1
- package/package.json +32 -18
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/project.json +0 -61
- package/src/hooks/__tests__/use-container.spec.mts +0 -53
- package/src/hooks/__tests__/use-invalidate.spec.mts +0 -80
- package/src/hooks/__tests__/use-optional-service.spec.mts +0 -233
- package/src/hooks/__tests__/use-service.spec.mts +0 -212
- package/src/hooks/__tests__/use-suspense-service.spec.mts +0 -286
- package/src/hooks/index.mts +0 -14
- package/src/hooks/use-container.mts +0 -61
- package/src/hooks/use-invalidate.mts +0 -41
- package/src/hooks/use-optional-service.mts +0 -276
- package/src/hooks/use-scope.mts +0 -87
- package/src/hooks/use-service.mts +0 -226
- package/src/hooks/use-suspense-service.mts +0 -234
- package/src/index.mts +0 -8
- package/src/providers/__tests__/scope-provider.spec.mts +0 -366
- package/src/providers/container-provider.mts +0 -18
- package/src/providers/context.mts +0 -15
- package/src/providers/index.mts +0 -5
- package/src/providers/scope-provider.mts +0 -90
- package/src/types.mts +0 -21
- package/tsconfig.json +0 -13
- package/tsdown.config.mts +0 -14
- package/vitest.config.mts +0 -12
package/src/hooks/use-scope.mts
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import type { ScopedContainer } from '@navios/di'
|
|
2
|
-
|
|
3
|
-
import { useContext } from 'react'
|
|
4
|
-
|
|
5
|
-
import { ScopedContainerContext } from '../providers/context.mjs'
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Hook to get the current scope ID.
|
|
9
|
-
* Returns null if not inside a ScopeProvider.
|
|
10
|
-
*/
|
|
11
|
-
export function useScope(): string | null {
|
|
12
|
-
const scopedContainer = useContext(ScopedContainerContext)
|
|
13
|
-
return scopedContainer?.getRequestId() ?? null
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Hook to get the current scope ID, throwing if not inside a ScopeProvider.
|
|
18
|
-
* Use this when your component requires a scope to function correctly.
|
|
19
|
-
*/
|
|
20
|
-
export function useScopeOrThrow(): string {
|
|
21
|
-
const scopeId = useScope()
|
|
22
|
-
if (scopeId === null) {
|
|
23
|
-
throw new Error(
|
|
24
|
-
'useScopeOrThrow must be used within a ScopeProvider. ' +
|
|
25
|
-
'Wrap your component tree with <ScopeProvider> to create a request scope.',
|
|
26
|
-
)
|
|
27
|
-
}
|
|
28
|
-
return scopeId
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Hook to get the current ScopedContainer.
|
|
33
|
-
* Returns null if not inside a ScopeProvider.
|
|
34
|
-
*
|
|
35
|
-
* Use this to access scope metadata or other ScopedContainer methods.
|
|
36
|
-
*
|
|
37
|
-
* @example
|
|
38
|
-
* ```tsx
|
|
39
|
-
* function TableRow() {
|
|
40
|
-
* const scope = useScopedContainer()
|
|
41
|
-
* const rowData = scope?.getMetadata('rowData')
|
|
42
|
-
* // ...
|
|
43
|
-
* }
|
|
44
|
-
* ```
|
|
45
|
-
*/
|
|
46
|
-
export function useScopedContainer(): ScopedContainer | null {
|
|
47
|
-
return useContext(ScopedContainerContext)
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
|
|
52
|
-
* Use this when your component requires a scope to function correctly.
|
|
53
|
-
*/
|
|
54
|
-
export function useScopedContainerOrThrow(): ScopedContainer {
|
|
55
|
-
const scopedContainer = useScopedContainer()
|
|
56
|
-
if (scopedContainer === null) {
|
|
57
|
-
throw new Error(
|
|
58
|
-
'useScopedContainerOrThrow must be used within a ScopeProvider. ' +
|
|
59
|
-
'Wrap your component tree with <ScopeProvider> to create a request scope.',
|
|
60
|
-
)
|
|
61
|
-
}
|
|
62
|
-
return scopedContainer
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Hook to get metadata from the current scope.
|
|
67
|
-
* Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
|
|
68
|
-
*
|
|
69
|
-
* @example
|
|
70
|
-
* ```tsx
|
|
71
|
-
* // In parent component:
|
|
72
|
-
* <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
|
|
73
|
-
* <ChildComponent />
|
|
74
|
-
* </ScopeProvider>
|
|
75
|
-
*
|
|
76
|
-
* // In child component:
|
|
77
|
-
* function ChildComponent() {
|
|
78
|
-
* const userId = useScopeMetadata<string>('userId')
|
|
79
|
-
* const theme = useScopeMetadata<'light' | 'dark'>('theme')
|
|
80
|
-
* // ...
|
|
81
|
-
* }
|
|
82
|
-
* ```
|
|
83
|
-
*/
|
|
84
|
-
export function useScopeMetadata<T = unknown>(key: string): T | undefined {
|
|
85
|
-
const scopedContainer = useContext(ScopedContainerContext)
|
|
86
|
-
return scopedContainer?.getMetadata(key) as T | undefined
|
|
87
|
-
}
|
|
@@ -1,226 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
AnyInjectableType,
|
|
3
|
-
BoundInjectionToken,
|
|
4
|
-
ClassType,
|
|
5
|
-
Factorable,
|
|
6
|
-
FactoryInjectionToken,
|
|
7
|
-
InjectionToken,
|
|
8
|
-
InjectionTokenSchemaType,
|
|
9
|
-
} from '@navios/di'
|
|
10
|
-
import type { z, ZodType } from 'zod/v4'
|
|
11
|
-
|
|
12
|
-
import { useCallback, useEffect, useReducer, useRef, useState } from 'react'
|
|
13
|
-
|
|
14
|
-
import type { Join, UnionToArray } from '../types.mjs'
|
|
15
|
-
|
|
16
|
-
import { useContainer, useRootContainer } from './use-container.mjs'
|
|
17
|
-
|
|
18
|
-
type ServiceState<T> =
|
|
19
|
-
| { status: 'idle' }
|
|
20
|
-
| { status: 'loading' }
|
|
21
|
-
| { status: 'success'; data: T }
|
|
22
|
-
| { status: 'error'; error: Error }
|
|
23
|
-
|
|
24
|
-
type ServiceAction<T> =
|
|
25
|
-
| { type: 'loading' }
|
|
26
|
-
| { type: 'success'; data: T }
|
|
27
|
-
| { type: 'error'; error: Error }
|
|
28
|
-
| { type: 'reset' }
|
|
29
|
-
|
|
30
|
-
function serviceReducer<T>(
|
|
31
|
-
state: ServiceState<T>,
|
|
32
|
-
action: ServiceAction<T>,
|
|
33
|
-
): ServiceState<T> {
|
|
34
|
-
switch (action.type) {
|
|
35
|
-
case 'loading':
|
|
36
|
-
return { status: 'loading' }
|
|
37
|
-
case 'success':
|
|
38
|
-
return { status: 'success', data: action.data }
|
|
39
|
-
case 'error':
|
|
40
|
-
return { status: 'error', error: action.error }
|
|
41
|
-
case 'reset':
|
|
42
|
-
return { status: 'idle' }
|
|
43
|
-
default:
|
|
44
|
-
return state
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export interface UseServiceResult<T> {
|
|
49
|
-
data: T | undefined
|
|
50
|
-
error: Error | undefined
|
|
51
|
-
isLoading: boolean
|
|
52
|
-
isSuccess: boolean
|
|
53
|
-
isError: boolean
|
|
54
|
-
refetch: () => void
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// #1 Simple class
|
|
58
|
-
export function useService<T extends ClassType>(
|
|
59
|
-
token: T,
|
|
60
|
-
): UseServiceResult<
|
|
61
|
-
InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>
|
|
62
|
-
>
|
|
63
|
-
|
|
64
|
-
// #2 Token with required Schema
|
|
65
|
-
export function useService<T, S extends InjectionTokenSchemaType>(
|
|
66
|
-
token: InjectionToken<T, S>,
|
|
67
|
-
args: z.input<S>,
|
|
68
|
-
): UseServiceResult<T>
|
|
69
|
-
|
|
70
|
-
// #3 Token with optional Schema
|
|
71
|
-
export function useService<
|
|
72
|
-
T,
|
|
73
|
-
S extends InjectionTokenSchemaType,
|
|
74
|
-
R extends boolean,
|
|
75
|
-
>(
|
|
76
|
-
token: InjectionToken<T, S, R>,
|
|
77
|
-
): R extends false
|
|
78
|
-
? UseServiceResult<T>
|
|
79
|
-
: S extends ZodType<infer Type>
|
|
80
|
-
? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`
|
|
81
|
-
: 'Error: Your token requires args'
|
|
82
|
-
|
|
83
|
-
// #4 Token with no Schema
|
|
84
|
-
export function useService<T>(
|
|
85
|
-
token: InjectionToken<T, undefined>,
|
|
86
|
-
): UseServiceResult<T>
|
|
87
|
-
|
|
88
|
-
export function useService<T>(
|
|
89
|
-
token: BoundInjectionToken<T, any>,
|
|
90
|
-
): UseServiceResult<T>
|
|
91
|
-
|
|
92
|
-
export function useService<T>(
|
|
93
|
-
token: FactoryInjectionToken<T, any>,
|
|
94
|
-
): UseServiceResult<T>
|
|
95
|
-
|
|
96
|
-
export function useService(
|
|
97
|
-
token:
|
|
98
|
-
| ClassType
|
|
99
|
-
| InjectionToken<any, any>
|
|
100
|
-
| BoundInjectionToken<any, any>
|
|
101
|
-
| FactoryInjectionToken<any, any>,
|
|
102
|
-
args?: unknown,
|
|
103
|
-
): UseServiceResult<any> {
|
|
104
|
-
// useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container
|
|
105
|
-
// This automatically handles request-scoped services correctly
|
|
106
|
-
const container = useContainer()
|
|
107
|
-
const rootContainer = useRootContainer()
|
|
108
|
-
|
|
109
|
-
// Try to get the instance synchronously first for better performance
|
|
110
|
-
// This avoids the async loading state when the instance is already cached
|
|
111
|
-
// We use a ref to track this so it doesn't cause effect re-runs
|
|
112
|
-
const initialSyncInstanceRef = useRef<any>(undefined)
|
|
113
|
-
const isFirstRenderRef = useRef(true)
|
|
114
|
-
|
|
115
|
-
if (isFirstRenderRef.current) {
|
|
116
|
-
initialSyncInstanceRef.current = container.tryGetSync(token, args)
|
|
117
|
-
isFirstRenderRef.current = false
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
const initialState: ServiceState<any> = initialSyncInstanceRef.current
|
|
121
|
-
? { status: 'success', data: initialSyncInstanceRef.current }
|
|
122
|
-
: { status: 'idle' }
|
|
123
|
-
|
|
124
|
-
const [state, dispatch] = useReducer(serviceReducer, initialState)
|
|
125
|
-
const instanceNameRef = useRef<string | null>(null)
|
|
126
|
-
const [refetchCounter, setRefetchCounter] = useState(0)
|
|
127
|
-
|
|
128
|
-
if (process.env.NODE_ENV === 'development') {
|
|
129
|
-
const argsRef = useRef<unknown>(args)
|
|
130
|
-
useEffect(() => {
|
|
131
|
-
if (argsRef.current !== args) {
|
|
132
|
-
if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {
|
|
133
|
-
console.log(`WARNING: useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
|
|
134
|
-
This is likely because you are using not memoized value that is not stable.
|
|
135
|
-
Please use a memoized value or use a different approach to pass the args.
|
|
136
|
-
Example:
|
|
137
|
-
const args = useMemo(() => ({ userId: '123' }), [])
|
|
138
|
-
return useService(UserToken, args)
|
|
139
|
-
`)
|
|
140
|
-
}
|
|
141
|
-
argsRef.current = args
|
|
142
|
-
}
|
|
143
|
-
}, [args])
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// Subscribe to invalidation events
|
|
147
|
-
useEffect(() => {
|
|
148
|
-
const eventBus = rootContainer.getEventBus()
|
|
149
|
-
let unsubscribe: (() => void) | undefined
|
|
150
|
-
let isMounted = true
|
|
151
|
-
|
|
152
|
-
// Fetch the service and set up subscription
|
|
153
|
-
const fetchAndSubscribe = async () => {
|
|
154
|
-
try {
|
|
155
|
-
// The container (either ScopedContainer or Container) handles resolution correctly
|
|
156
|
-
const instance = await container.get(
|
|
157
|
-
// @ts-expect-error - token is valid
|
|
158
|
-
token as AnyInjectableType,
|
|
159
|
-
args as any,
|
|
160
|
-
)
|
|
161
|
-
|
|
162
|
-
if (!isMounted) return
|
|
163
|
-
|
|
164
|
-
// Get instance name for event subscription
|
|
165
|
-
const instanceName = container.calculateInstanceName(token, args)
|
|
166
|
-
if (instanceName) {
|
|
167
|
-
instanceNameRef.current = instanceName
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
dispatch({ type: 'success', data: instance })
|
|
171
|
-
|
|
172
|
-
// Set up subscription after we have the instance
|
|
173
|
-
if (instanceName) {
|
|
174
|
-
unsubscribe = eventBus.on(instanceName, 'destroy', () => {
|
|
175
|
-
// Re-fetch when the service is invalidated
|
|
176
|
-
if (isMounted) {
|
|
177
|
-
dispatch({ type: 'loading' })
|
|
178
|
-
void fetchAndSubscribe()
|
|
179
|
-
}
|
|
180
|
-
})
|
|
181
|
-
}
|
|
182
|
-
} catch (error) {
|
|
183
|
-
if (isMounted) {
|
|
184
|
-
dispatch({ type: 'error', error: error as Error })
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// If we already have a sync instance from initial render, just set up subscription
|
|
190
|
-
// Otherwise, fetch async
|
|
191
|
-
const syncInstance = initialSyncInstanceRef.current
|
|
192
|
-
if (syncInstance && refetchCounter === 0) {
|
|
193
|
-
const instanceName = container.calculateInstanceName(token, args)
|
|
194
|
-
if (instanceName) {
|
|
195
|
-
instanceNameRef.current = instanceName
|
|
196
|
-
unsubscribe = eventBus.on(instanceName, 'destroy', () => {
|
|
197
|
-
if (isMounted) {
|
|
198
|
-
dispatch({ type: 'loading' })
|
|
199
|
-
void fetchAndSubscribe()
|
|
200
|
-
}
|
|
201
|
-
})
|
|
202
|
-
}
|
|
203
|
-
} else {
|
|
204
|
-
dispatch({ type: 'loading' })
|
|
205
|
-
void fetchAndSubscribe()
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
return () => {
|
|
209
|
-
isMounted = false
|
|
210
|
-
unsubscribe?.()
|
|
211
|
-
}
|
|
212
|
-
}, [container, rootContainer, token, args, refetchCounter])
|
|
213
|
-
|
|
214
|
-
const refetch = useCallback(() => {
|
|
215
|
-
setRefetchCounter((c) => c + 1)
|
|
216
|
-
}, [])
|
|
217
|
-
|
|
218
|
-
return {
|
|
219
|
-
data: state.status === 'success' ? state.data : undefined,
|
|
220
|
-
error: state.status === 'error' ? state.error : undefined,
|
|
221
|
-
isLoading: state.status === 'loading',
|
|
222
|
-
isSuccess: state.status === 'success',
|
|
223
|
-
isError: state.status === 'error',
|
|
224
|
-
refetch,
|
|
225
|
-
}
|
|
226
|
-
}
|
|
@@ -1,234 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
BoundInjectionToken,
|
|
3
|
-
ClassType,
|
|
4
|
-
Container,
|
|
5
|
-
Factorable,
|
|
6
|
-
FactoryInjectionToken,
|
|
7
|
-
InjectionToken,
|
|
8
|
-
InjectionTokenSchemaType,
|
|
9
|
-
} from '@navios/di'
|
|
10
|
-
import type { z, ZodType } from 'zod/v4'
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'
|
|
14
|
-
|
|
15
|
-
import type { Join, UnionToArray } from '../types.mjs'
|
|
16
|
-
|
|
17
|
-
import { useContainer, useRootContainer } from './use-container.mjs'
|
|
18
|
-
|
|
19
|
-
// Cache entry for suspense
|
|
20
|
-
interface CacheEntry<T> {
|
|
21
|
-
promise: Promise<T> | null
|
|
22
|
-
result: T | undefined
|
|
23
|
-
error: Error | undefined
|
|
24
|
-
status: 'pending' | 'resolved' | 'rejected'
|
|
25
|
-
version: number // Increment on each fetch to track changes
|
|
26
|
-
subscribers: Set<() => void>
|
|
27
|
-
instanceName: string | null
|
|
28
|
-
unsubscribe: (() => void) | undefined
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// Global cache for service instances (per container + token + args combination)
|
|
32
|
-
const cacheMap = new WeakMap<object, Map<string, CacheEntry<any>>>()
|
|
33
|
-
|
|
34
|
-
function getCacheKey(token: any, args: unknown): string {
|
|
35
|
-
const tokenId =
|
|
36
|
-
typeof token === 'function'
|
|
37
|
-
? token.name
|
|
38
|
-
: token.id || token.token?.id || String(token)
|
|
39
|
-
return `${tokenId}:${JSON.stringify(args ?? null)}`
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function getCache(container: object): Map<string, CacheEntry<any>> {
|
|
43
|
-
let cache = cacheMap.get(container)
|
|
44
|
-
if (!cache) {
|
|
45
|
-
cache = new Map()
|
|
46
|
-
cacheMap.set(container, cache)
|
|
47
|
-
}
|
|
48
|
-
return cache
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Sets up invalidation subscription for a cache entry if not already subscribed.
|
|
53
|
-
* When the service is destroyed, clears the cache and notifies subscribers.
|
|
54
|
-
*/
|
|
55
|
-
function setupInvalidationSubscription(
|
|
56
|
-
entry: CacheEntry<any>,
|
|
57
|
-
rootContainer: Container,
|
|
58
|
-
): void {
|
|
59
|
-
if (entry.unsubscribe || !entry.instanceName) return
|
|
60
|
-
|
|
61
|
-
const eventBus = rootContainer.getEventBus()
|
|
62
|
-
entry.unsubscribe = eventBus.on(entry.instanceName, 'destroy', () => {
|
|
63
|
-
// Clear cache and notify subscribers to re-fetch
|
|
64
|
-
entry.result = undefined
|
|
65
|
-
entry.error = undefined
|
|
66
|
-
entry.status = 'pending'
|
|
67
|
-
entry.promise = null
|
|
68
|
-
// Notify all subscribers
|
|
69
|
-
entry.subscribers.forEach((callback) => callback())
|
|
70
|
-
})
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// #1 Simple class
|
|
74
|
-
export function useSuspenseService<T extends ClassType>(
|
|
75
|
-
token: T,
|
|
76
|
-
): InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>
|
|
77
|
-
|
|
78
|
-
// #2 Token with required Schema
|
|
79
|
-
export function useSuspenseService<T, S extends InjectionTokenSchemaType>(
|
|
80
|
-
token: InjectionToken<T, S>,
|
|
81
|
-
args: z.input<S>,
|
|
82
|
-
): T
|
|
83
|
-
|
|
84
|
-
// #3 Token with optional Schema
|
|
85
|
-
export function useSuspenseService<
|
|
86
|
-
T,
|
|
87
|
-
S extends InjectionTokenSchemaType,
|
|
88
|
-
R extends boolean,
|
|
89
|
-
>(
|
|
90
|
-
token: InjectionToken<T, S, R>,
|
|
91
|
-
): R extends false
|
|
92
|
-
? T
|
|
93
|
-
: S extends ZodType<infer Type>
|
|
94
|
-
? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`
|
|
95
|
-
: 'Error: Your token requires args'
|
|
96
|
-
|
|
97
|
-
// #4 Token with no Schema
|
|
98
|
-
export function useSuspenseService<T>(token: InjectionToken<T, undefined>): T
|
|
99
|
-
|
|
100
|
-
export function useSuspenseService<T>(token: BoundInjectionToken<T, any>): T
|
|
101
|
-
|
|
102
|
-
export function useSuspenseService<T>(token: FactoryInjectionToken<T, any>): T
|
|
103
|
-
|
|
104
|
-
export function useSuspenseService(
|
|
105
|
-
token:
|
|
106
|
-
| ClassType
|
|
107
|
-
| InjectionToken<any, any>
|
|
108
|
-
| BoundInjectionToken<any, any>
|
|
109
|
-
| FactoryInjectionToken<any, any>,
|
|
110
|
-
args?: unknown,
|
|
111
|
-
): any {
|
|
112
|
-
// useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container
|
|
113
|
-
const container = useContainer()
|
|
114
|
-
const rootContainer = useRootContainer()
|
|
115
|
-
const cache = getCache(container)
|
|
116
|
-
const cacheKey = getCacheKey(token, args)
|
|
117
|
-
const entryRef = useRef<CacheEntry<any> | null>(null)
|
|
118
|
-
if (process.env.NODE_ENV === 'development') {
|
|
119
|
-
const argsRef = useRef<unknown>(args)
|
|
120
|
-
useEffect(() => {
|
|
121
|
-
if (argsRef.current !== args) {
|
|
122
|
-
if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {
|
|
123
|
-
console.log(`WARNING: useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
|
|
124
|
-
This is likely because you are using not memoized value that is not stable.
|
|
125
|
-
Please use a memoized value or use a different approach to pass the args.
|
|
126
|
-
Example:
|
|
127
|
-
const args = useMemo(() => ({ userId: '123' }), [])
|
|
128
|
-
return useService(UserToken, args)
|
|
129
|
-
`)
|
|
130
|
-
}
|
|
131
|
-
argsRef.current = args
|
|
132
|
-
}
|
|
133
|
-
}, [args])
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// Initialize or get cache entry
|
|
137
|
-
if (!cache.has(cacheKey)) {
|
|
138
|
-
// Try to get the instance synchronously first for better performance
|
|
139
|
-
// This avoids suspense when the instance is already cached
|
|
140
|
-
const syncInstance = container.tryGetSync(token, args)
|
|
141
|
-
|
|
142
|
-
const instanceName = container.calculateInstanceName(token, args)
|
|
143
|
-
const entry: CacheEntry<any> = {
|
|
144
|
-
promise: null,
|
|
145
|
-
result: syncInstance ?? undefined,
|
|
146
|
-
error: undefined,
|
|
147
|
-
status: syncInstance ? 'resolved' : 'pending',
|
|
148
|
-
version: 0,
|
|
149
|
-
subscribers: new Set(),
|
|
150
|
-
instanceName,
|
|
151
|
-
unsubscribe: undefined,
|
|
152
|
-
}
|
|
153
|
-
cache.set(cacheKey, entry)
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
const entry = cache.get(cacheKey)!
|
|
157
|
-
entryRef.current = entry
|
|
158
|
-
|
|
159
|
-
// Function to fetch the service
|
|
160
|
-
const fetchService = useCallback(() => {
|
|
161
|
-
const currentEntry = entryRef.current
|
|
162
|
-
if (!currentEntry) return
|
|
163
|
-
|
|
164
|
-
currentEntry.status = 'pending'
|
|
165
|
-
currentEntry.version++ // Increment version to signal change to useSyncExternalStore
|
|
166
|
-
currentEntry.promise = (container.get as any)(token, args)
|
|
167
|
-
.then((instance: any) => {
|
|
168
|
-
currentEntry.result = instance
|
|
169
|
-
currentEntry.status = 'resolved'
|
|
170
|
-
|
|
171
|
-
// Subscribe to invalidation events if not already subscribed
|
|
172
|
-
setupInvalidationSubscription(currentEntry, rootContainer)
|
|
173
|
-
|
|
174
|
-
// Notify subscribers
|
|
175
|
-
currentEntry.subscribers.forEach((callback) => callback())
|
|
176
|
-
return instance
|
|
177
|
-
})
|
|
178
|
-
.catch((error: Error) => {
|
|
179
|
-
currentEntry.error = error
|
|
180
|
-
currentEntry.status = 'rejected'
|
|
181
|
-
throw error
|
|
182
|
-
})
|
|
183
|
-
|
|
184
|
-
return currentEntry.promise
|
|
185
|
-
}, [container, rootContainer, token, args])
|
|
186
|
-
|
|
187
|
-
// Subscribe to cache changes
|
|
188
|
-
const subscribe = useCallback(
|
|
189
|
-
(callback: () => void) => {
|
|
190
|
-
entry.subscribers.add(callback)
|
|
191
|
-
return () => {
|
|
192
|
-
entry.subscribers.delete(callback)
|
|
193
|
-
}
|
|
194
|
-
},
|
|
195
|
-
[entry],
|
|
196
|
-
)
|
|
197
|
-
|
|
198
|
-
// Get snapshot of current state - include version to detect invalidation
|
|
199
|
-
const getSnapshot = useCallback(() => {
|
|
200
|
-
return `${entry.status}:${entry.version}`
|
|
201
|
-
}, [entry])
|
|
202
|
-
|
|
203
|
-
// Use sync external store to track cache state
|
|
204
|
-
useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
|
|
205
|
-
|
|
206
|
-
// Set up subscription for sync instances that don't have one yet
|
|
207
|
-
useEffect(() => {
|
|
208
|
-
const currentEntry = entryRef.current
|
|
209
|
-
if (
|
|
210
|
-
currentEntry &&
|
|
211
|
-
currentEntry.status === 'resolved' &&
|
|
212
|
-
currentEntry.instanceName &&
|
|
213
|
-
!currentEntry.unsubscribe
|
|
214
|
-
) {
|
|
215
|
-
setupInvalidationSubscription(currentEntry, rootContainer)
|
|
216
|
-
}
|
|
217
|
-
}, [rootContainer, entry])
|
|
218
|
-
|
|
219
|
-
// Start fetching if not already
|
|
220
|
-
if (entry.status === 'pending' && !entry.promise) {
|
|
221
|
-
fetchService()
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// Suspense behavior
|
|
225
|
-
if (entry.status === 'pending') {
|
|
226
|
-
throw entry.promise
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
if (entry.status === 'rejected') {
|
|
230
|
-
throw entry.error
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
return entry.result
|
|
234
|
-
}
|