@navios/di-react 1.0.0-alpha.3 โ†’ 2.0.0-alpha.1

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +47 -1
  2. package/README.md +45 -665
  3. package/lib/index.cjs +573 -0
  4. package/lib/index.cjs.map +1 -0
  5. package/lib/index.d.cts +262 -0
  6. package/lib/index.d.cts.map +1 -0
  7. package/lib/index.d.mts +159 -140
  8. package/lib/index.d.mts.map +1 -1
  9. package/lib/index.mjs +371 -381
  10. package/lib/index.mjs.map +1 -1
  11. package/package.json +32 -18
  12. package/coverage/base.css +0 -224
  13. package/coverage/block-navigation.js +0 -87
  14. package/coverage/clover.xml +0 -270
  15. package/coverage/coverage-final.json +0 -10
  16. package/coverage/favicon.png +0 -0
  17. package/coverage/hooks/index.html +0 -191
  18. package/coverage/hooks/use-container.mts.html +0 -268
  19. package/coverage/hooks/use-invalidate.mts.html +0 -208
  20. package/coverage/hooks/use-optional-service.mts.html +0 -910
  21. package/coverage/hooks/use-scope.mts.html +0 -346
  22. package/coverage/hooks/use-service.mts.html +0 -760
  23. package/coverage/hooks/use-suspense-service.mts.html +0 -784
  24. package/coverage/index.html +0 -131
  25. package/coverage/prettify.css +0 -1
  26. package/coverage/prettify.js +0 -2
  27. package/coverage/providers/container-provider.mts.html +0 -139
  28. package/coverage/providers/context.mts.html +0 -130
  29. package/coverage/providers/index.html +0 -146
  30. package/coverage/providers/scope-provider.mts.html +0 -355
  31. package/coverage/sort-arrow-sprite.png +0 -0
  32. package/coverage/sorter.js +0 -210
  33. package/lib/index.d.ts +0 -243
  34. package/lib/index.d.ts.map +0 -1
  35. package/lib/index.js +0 -582
  36. package/lib/index.js.map +0 -1
  37. package/project.json +0 -61
  38. package/src/hooks/__tests__/use-container.spec.mts +0 -143
  39. package/src/hooks/__tests__/use-invalidate.spec.mts +0 -80
  40. package/src/hooks/__tests__/use-optional-service.spec.mts +0 -233
  41. package/src/hooks/__tests__/use-scope.spec.mts +0 -293
  42. package/src/hooks/__tests__/use-service.spec.mts +0 -212
  43. package/src/hooks/__tests__/use-suspense-service.spec.mts +0 -286
  44. package/src/hooks/index.mts +0 -14
  45. package/src/hooks/use-container.mts +0 -61
  46. package/src/hooks/use-invalidate.mts +0 -41
  47. package/src/hooks/use-optional-service.mts +0 -275
  48. package/src/hooks/use-scope.mts +0 -87
  49. package/src/hooks/use-service.mts +0 -225
  50. package/src/hooks/use-suspense-service.mts +0 -233
  51. package/src/index.mts +0 -8
  52. package/src/providers/__tests__/scope-provider.spec.mts +0 -366
  53. package/src/providers/container-provider.mts +0 -18
  54. package/src/providers/context.mts +0 -15
  55. package/src/providers/index.mts +0 -5
  56. package/src/providers/scope-provider.mts +0 -90
  57. package/src/types.mts +0 -21
  58. package/tsconfig.json +0 -13
  59. package/tsdown.config.mts +0 -14
  60. package/vitest.config.mts +0 -12
package/README.md CHANGED
@@ -1,703 +1,83 @@
1
1
  # @navios/di-react
2
2
 
3
- React integration for `@navios/di` dependency injection container. Provides a set of hooks and providers to seamlessly use dependency injection in React applications with automatic service lifecycle management, invalidation subscriptions, and request-scoped service isolation.
3
+ React bindings for [`@navios/di`](https://www.npmjs.com/package/@navios/di). A provider puts a container in context, and hooks resolve services from it, re-render when a service is invalidated, and create scopes that live as long as a part of the component tree.
4
4
 
5
- ## Features
5
+ **[Documentation](https://navios.tech/docs/di/react/)** ยท [API reference](https://navios.tech/docs/di/reference/react-api)
6
6
 
7
- - **๐ŸŽฏ Type-Safe**: Full TypeScript support with compile-time type checking
8
- - **๐ŸŽจ Flexible API**: Support for classes, injection tokens, and factory tokens
9
- - **โš™๏ธ Zod Integration**: Type-safe arguments with Zod schema validation
10
- - **๐Ÿ”„ Automatic Invalidation**: Services automatically re-fetch when invalidated
11
- - **โšก React Suspense Support**: Use `useSuspenseService` with React Suspense for declarative loading
12
- - **๐Ÿ”Œ Request Scopes**: Isolate services per request/component tree with `ScopeProvider`
13
- - **๐Ÿ“ฆ Optional Services**: Load services that may not be registered with `useOptionalService`
14
- - **๐Ÿš€ Performance**: Synchronous resolution when instances are already cached
15
-
16
- ## Installation
7
+ ## Install
17
8
 
18
9
  ```bash
19
- npm install @navios/di-react @navios/di react
20
- # or
21
- yarn add @navios/di-react @navios/di react
22
- # or
23
- pnpm add @navios/di-react @navios/di react
24
- ```
25
-
26
- ## Quick Start
27
-
28
- ### 1. Set up the Container Provider
29
-
30
- Wrap your application with `ContainerProvider`:
31
-
32
- ```tsx
33
- import { Container } from '@navios/di'
34
- import { ContainerProvider } from '@navios/di-react'
35
-
36
- const container = new Container()
37
-
38
- function App() {
39
- return (
40
- <ContainerProvider container={container}>
41
- <YourApp />
42
- </ContainerProvider>
43
- )
44
- }
45
- ```
46
-
47
- ### 2. Use Services in Components
48
-
49
- ```tsx
50
- import { useService } from '@navios/di-react'
51
- import { MyService } from './services/my-service'
52
-
53
- function MyComponent() {
54
- const { data, isLoading, isError, error } = useService(MyService)
55
-
56
- if (isLoading) return <div>Loading...</div>
57
- if (isError) return <div>Error: {error?.message}</div>
58
-
59
- return <div>{data.someValue}</div>
60
- }
61
- ```
62
-
63
- ## Core Concepts
64
-
65
- ### Container Provider
66
-
67
- The `ContainerProvider` makes the DI container available to all child components via React context. You should wrap your application root with it.
68
-
69
- ```tsx
70
- import { Container } from '@navios/di'
71
- import { ContainerProvider } from '@navios/di-react'
72
-
73
- const container = new Container()
74
-
75
- function App() {
76
- return (
77
- <ContainerProvider container={container}>
78
- <YourApp />
79
- </ContainerProvider>
80
- )
81
- }
82
- ```
83
-
84
- **Note**: The container prop should be stable. Avoid creating a new container on every render. If you need to create the container dynamically, use `useMemo` or `useState`.
85
-
86
- ### Scope Provider
87
-
88
- `ScopeProvider` creates an isolated request scope for dependency injection. Services with `scope: 'Request'` will be instantiated once per scope and shared among all components within that provider.
89
-
90
- This is useful for:
91
-
92
- - **Table rows** that need isolated state
93
- - **Modal dialogs** with their own service instances
94
- - **Multi-tenant scenarios**
95
- - **Any case where you need isolated service instances**
96
-
97
- ```tsx
98
- import { ScopeProvider } from '@navios/di-react'
99
-
100
- function Table({ rows }) {
101
- return (
102
- <table>
103
- {rows.map((row) => (
104
- <ScopeProvider
105
- key={row.id}
106
- scopeId={row.id}
107
- metadata={{ rowData: row }}
108
- >
109
- <TableRow />
110
- </ScopeProvider>
111
- ))}
112
- </table>
113
- )
114
- }
115
- ```
116
-
117
- ## Hooks
118
-
119
- ### useContainer
120
-
121
- Access the container directly. Automatically returns the `ScopedContainer` if inside a `ScopeProvider`, otherwise returns the root `Container`.
122
-
123
- ```tsx
124
- import { useContainer } from '@navios/di-react'
125
-
126
- function MyComponent() {
127
- const container = useContainer()
128
-
129
- const handleClick = async () => {
130
- const service = await container.get(MyService)
131
- service.doSomething()
132
- }
133
-
134
- return <button onClick={handleClick}>Do Something</button>
135
- }
136
- ```
137
-
138
- ### useRootContainer
139
-
140
- Get the root container regardless of whether you're inside a `ScopeProvider`. Useful when you need to create new request scopes programmatically.
141
-
142
- ```tsx
143
- import { useRootContainer } from '@navios/di-react'
144
-
145
- function MyComponent() {
146
- const rootContainer = useRootContainer()
147
-
148
- const createNewScope = () => {
149
- const scopedContainer = rootContainer.beginRequest('new-scope')
150
- // Use scopedContainer...
151
- }
152
-
153
- return <button onClick={createNewScope}>Create Scope</button>
154
- }
155
- ```
156
-
157
- ### useService
158
-
159
- Fetch a service with loading/error states. Automatically re-fetches when the service is invalidated.
160
-
161
- ```tsx
162
- import { useService } from '@navios/di-react'
163
- import { MyService } from './services/my-service'
164
-
165
- function MyComponent() {
166
- const { data, isLoading, isError, error, refetch } = useService(MyService)
167
-
168
- if (isLoading) return <div>Loading...</div>
169
- if (isError) return <div>Error: {error?.message}</div>
170
-
171
- return (
172
- <div>
173
- <p>{data.someValue}</p>
174
- <button onClick={refetch}>Refresh</button>
175
- </div>
176
- )
177
- }
178
- ```
179
-
180
- #### With Injection Tokens and Arguments
181
-
182
- ```tsx
183
- import { InjectionToken } from '@navios/di'
184
- import { useService } from '@navios/di-react'
185
- import { useMemo } from 'react'
186
- import { z } from 'zod'
187
-
188
- const UserSchema = z.object({ userId: z.string() })
189
- const UserToken = InjectionToken.create<
190
- { userId: string; name: string },
191
- typeof UserSchema
192
- >('User', UserSchema)
193
-
194
- function UserProfile({ userId }: { userId: string }) {
195
- // Important: Memoize args to avoid unnecessary re-fetches
196
- const args = useMemo(() => ({ userId }), [userId])
197
- const { data: user, isLoading } = useService(UserToken, args)
198
-
199
- if (isLoading) return <div>Loading...</div>
200
-
201
- return <div>{user.name}</div>
202
- }
10
+ npm install @navios/di-react@next @navios/di@next
203
11
  ```
204
12
 
205
- **Important**: Always memoize arguments passed to `useService` to prevent unnecessary re-fetches. The hook uses reference equality to determine if arguments have changed.
13
+ The 2.0 alpha is published under the `next` tag. All `@navios` packages of a project must have the same alpha version, because an alpha may break between releases.
206
14
 
207
- ### useSuspenseService
15
+ Requires `react` `^18.0.0 || ^19.0.0`. The services are compiled by your bundler, so it has to handle standard TC39 decorators.
208
16
 
209
- Use with React Suspense for a cleaner loading experience. Also subscribes to service invalidation.
17
+ ## Example
210
18
 
211
19
  ```tsx
20
+ import { Container, Injectable } from '@navios/di'
21
+ import { ContainerProvider, useService, useSuspenseService } from '@navios/di-react'
212
22
  import { Suspense } from 'react'
213
- import { useSuspenseService } from '@navios/di-react'
214
- import { MyService } from './services/my-service'
215
-
216
- function MyComponent() {
217
- const service = useSuspenseService(MyService)
218
-
219
- return <div>{service.someValue}</div>
220
- }
221
-
222
- function App() {
223
- return (
224
- <Suspense fallback={<div>Loading...</div>}>
225
- <MyComponent />
226
- </Suspense>
227
- )
228
- }
229
- ```
230
-
231
- #### Error Boundaries
232
-
233
- When using `useSuspenseService`, errors are thrown to the nearest error boundary. Make sure to wrap your components with an error boundary:
234
-
235
- ```tsx
236
- import { ErrorBoundary } from 'react-error-boundary'
237
- import { Suspense } from 'react'
238
- import { useSuspenseService } from '@navios/di-react'
239
-
240
- function ErrorFallback({ error }) {
241
- return <div>Error: {error.message}</div>
242
- }
243
-
244
- function App() {
245
- return (
246
- <ErrorBoundary FallbackComponent={ErrorFallback}>
247
- <Suspense fallback={<div>Loading...</div>}>
248
- <MyComponent />
249
- </Suspense>
250
- </ErrorBoundary>
251
- )
252
- }
253
- ```
254
-
255
- ### useOptionalService
256
-
257
- Load a service that may not be registered. Unlike `useService`, this hook does NOT throw an error if the service is not registered. Instead, it returns `isNotFound: true`.
258
-
259
- This is useful for:
260
-
261
- - **Optional dependencies** that may or may not be configured
262
- - **Feature flags** where a service might not be available
263
- - **Plugins or extensions** that are conditionally registered
264
-
265
- ```tsx
266
- import { useOptionalService } from '@navios/di-react'
267
-
268
- function Analytics() {
269
- const {
270
- data: analytics,
271
- isNotFound,
272
- isLoading,
273
- } = useOptionalService(AnalyticsService)
274
-
275
- if (isLoading) return null
276
- if (isNotFound) {
277
- // Analytics service not configured, skip tracking
278
- return null
279
- }
280
-
281
- return <AnalyticsTracker service={analytics} />
282
- }
283
- ```
284
-
285
- ### useInvalidateInstance
286
-
287
- Invalidate a service instance directly without knowing its token.
288
-
289
- ```tsx
290
- import { useService, useInvalidateInstance } from '@navios/di-react'
291
-
292
- function UserProfile() {
293
- const { data: user } = useService(UserService)
294
- const invalidateInstance = useInvalidateInstance()
295
-
296
- const handleRefresh = () => {
297
- if (user) {
298
- invalidateInstance(user)
299
- }
300
- }
301
-
302
- return (
303
- <div>
304
- <span>{user?.name}</span>
305
- <button onClick={handleRefresh}>Refresh</button>
306
- </div>
307
- )
308
- }
309
- ```
310
23
 
311
- ### useScope
312
-
313
- Get the current scope ID. Returns `null` if not inside a `ScopeProvider`.
314
-
315
- ```tsx
316
- import { useScope } from '@navios/di-react'
317
-
318
- function MyComponent() {
319
- const scopeId = useScope()
320
-
321
- if (!scopeId) {
322
- return <div>Not in a scope</div>
24
+ @Injectable()
25
+ class GreetingService {
26
+ greet(name: string) {
27
+ return `Hello, ${name}`
323
28
  }
324
-
325
- return <div>Current scope: {scopeId}</div>
326
- }
327
- ```
328
-
329
- ### useScopeOrThrow
330
-
331
- Get the current scope ID, throwing an error if not inside a `ScopeProvider`.
332
-
333
- ```tsx
334
- import { useScopeOrThrow } from '@navios/di-react'
335
-
336
- function MyComponent() {
337
- const scopeId = useScopeOrThrow() // Throws if not in ScopeProvider
338
-
339
- return <div>Current scope: {scopeId}</div>
340
- }
341
- ```
342
-
343
- ### useScopedContainer
344
-
345
- Get the current `ScopedContainer`. Returns `null` if not inside a `ScopeProvider`.
346
-
347
- ```tsx
348
- import { useScopedContainer } from '@navios/di-react'
349
-
350
- function TableRow() {
351
- const scope = useScopedContainer()
352
- const rowData = scope?.getMetadata('rowData')
353
-
354
- return <tr>{/* ... */}</tr>
355
29
  }
356
- ```
357
30
 
358
- ### useScopedContainerOrThrow
359
-
360
- Get the current `ScopedContainer`, throwing an error if not inside a `ScopeProvider`.
31
+ const container = new Container()
361
32
 
362
- ```tsx
363
- import { useScopedContainerOrThrow } from '@navios/di-react'
33
+ function Greeting({ name }: { name: string }) {
34
+ const { data: greetings, error } = useService(GreetingService)
364
35
 
365
- function TableRow() {
366
- const scope = useScopedContainerOrThrow()
367
- const rowData = scope.getMetadata('rowData')
36
+ if (error) return <p>{error.message}</p>
37
+ if (!greetings) return <p>Loadingโ€ฆ</p>
368
38
 
369
- return <tr>{/* ... */}</tr>
39
+ return <p>{greetings.greet(name)}</p>
370
40
  }
371
- ```
372
41
 
373
- ### useScopeMetadata
42
+ function SuspendingGreeting({ name }: { name: string }) {
43
+ const greetings = useSuspenseService(GreetingService)
374
44
 
375
- Get metadata from the current scope. Returns `undefined` if not inside a `ScopeProvider` or if the key doesn't exist.
376
-
377
- ```tsx
378
- import { useScopeMetadata } from '@navios/di-react'
379
-
380
- // In parent component:
381
- ;<ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
382
- <ChildComponent />
383
- </ScopeProvider>
384
-
385
- // In child component:
386
- function ChildComponent() {
387
- const userId = useScopeMetadata<string>('userId')
388
- const theme = useScopeMetadata<'light' | 'dark'>('theme')
389
-
390
- return (
391
- <div>
392
- User: {userId}, Theme: {theme}
393
- </div>
394
- )
45
+ return <p>{greetings.greet(name)}</p>
395
46
  }
396
- ```
397
-
398
- ## Service Invalidation
399
-
400
- Both `useService` and `useSuspenseService` automatically subscribe to service invalidation events via the DI container's event bus. When a service is invalidated (e.g., via `container.invalidate(service)` or `useInvalidateInstance`), the hooks will automatically:
401
-
402
- 1. Clear the cached instance
403
- 2. Re-fetch the service
404
- 3. Update the component with the new instance
405
-
406
- This enables reactive updates when services change, making it easy to implement features like:
407
-
408
- - **Cache invalidation** after mutations
409
- - **Real-time updates** when data changes
410
- - **Refresh on user action** (e.g., pull-to-refresh)
411
-
412
- ```tsx
413
- function UserList() {
414
- const { data: users } = useService(UserService)
415
- const invalidateInstance = useInvalidateInstance()
416
-
417
- const handleCreateUser = async () => {
418
- await createUser(newUser)
419
- if (users) {
420
- invalidateInstance(users) // Automatically refreshes all components using UserService
421
- }
422
- }
423
47
 
48
+ export function App() {
424
49
  return (
425
- <div>
426
- {users.map((user) => (
427
- <UserItem key={user.id} user={user} />
428
- ))}
429
- <button onClick={handleCreateUser}>Add User</button>
430
- </div>
50
+ <ContainerProvider container={container}>
51
+ <Greeting name="Ada" />
52
+ <Suspense fallback={<p>Loadingโ€ฆ</p>}>
53
+ <SuspendingGreeting name="Grace" />
54
+ </Suspense>
55
+ </ContainerProvider>
431
56
  )
432
57
  }
433
58
  ```
434
59
 
435
- ## Best Practices
436
-
437
- ### 1. Memoize Arguments
438
-
439
- Always memoize arguments passed to hooks that accept them:
440
-
441
- ```tsx
442
- // โœ… Good
443
- const args = useMemo(() => ({ userId }), [userId])
444
- const { data } = useService(UserToken, args)
445
-
446
- // โŒ Bad - causes unnecessary re-fetches
447
- const { data } = useService(UserToken, { userId })
448
- ```
449
-
450
- ### 2. Stable Container Reference
451
-
452
- Keep your container reference stable:
453
-
454
- ```tsx
455
- // โœ… Good
456
- const container = useMemo(() => new Container(), [])
457
-
458
- // โŒ Bad - creates new container on every render
459
- const container = new Container()
460
- ```
461
-
462
- ### 3. Use Error Boundaries with Suspense
463
-
464
- When using `useSuspenseService`, always wrap with an error boundary:
465
-
466
- ```tsx
467
- <ErrorBoundary FallbackComponent={ErrorFallback}>
468
- <Suspense fallback={<Loading />}>
469
- <Component />
470
- </Suspense>
471
- </ErrorBoundary>
472
- ```
473
-
474
- ### 4. Scope Isolation
475
-
476
- Use `ScopeProvider` when you need isolated service instances:
477
-
478
- ```tsx
479
- // Each row gets its own service instance
480
- {
481
- rows.map((row) => (
482
- <ScopeProvider key={row.id} scopeId={row.id}>
483
- <TableRow />
484
- </ScopeProvider>
485
- ))
486
- }
487
- ```
488
-
489
- ### 5. Optional Services for Feature Flags
490
-
491
- Use `useOptionalService` for conditionally available services:
492
-
493
- ```tsx
494
- function FeatureComponent() {
495
- const { data: feature, isNotFound } = useOptionalService(FeatureService)
496
-
497
- if (isNotFound) return null // Feature not enabled
498
-
499
- return <FeatureUI service={feature} />
500
- }
501
- ```
502
-
503
- ## API Reference
504
-
505
- ### ContainerProvider
506
-
507
- | Prop | Type | Description |
508
- | ----------- | ----------- | -------------------------------------------- |
509
- | `container` | `Container` | The DI container instance (should be stable) |
510
- | `children` | `ReactNode` | Child components |
511
-
512
- ### ScopeProvider
513
-
514
- | Prop | Type | Description | Default |
515
- | ---------- | -------------------------- | -------------------------------------------------------------------------- | ----------- |
516
- | `scopeId` | `string?` | Optional explicit scope ID. If not provided, a unique ID will be generated | `undefined` |
517
- | `metadata` | `Record<string, unknown>?` | Optional metadata to attach to the request context | `undefined` |
518
- | `priority` | `number?` | Priority for service resolution. Higher priority scopes take precedence | `100` |
519
- | `children` | `ReactNode` | Child components | - |
520
-
521
- ### useContainer
522
-
523
- ```ts
524
- function useContainer(): IContainer
525
- ```
526
-
527
- Returns the container from context. Returns `ScopedContainer` if inside a `ScopeProvider`, otherwise returns the root `Container`. Throws if used outside of `ContainerProvider`.
528
-
529
- ### useRootContainer
530
-
531
- ```ts
532
- function useRootContainer(): Container
533
- ```
534
-
535
- Returns the root `Container` regardless of whether you're inside a `ScopeProvider`. Throws if used outside of `ContainerProvider`.
536
-
537
- ### useService
538
-
539
- ```ts
540
- function useService<T>(token: ClassType): UseServiceResult<InstanceType<T>>
541
- function useService<T, S>(
542
- token: InjectionToken<T, S>,
543
- args: z.input<S>,
544
- ): UseServiceResult<T>
545
- function useService<T>(token: InjectionToken<T, undefined>): UseServiceResult<T>
546
- // ... other overloads
547
-
548
- interface UseServiceResult<T> {
549
- data: T | undefined
550
- error: Error | undefined
551
- isLoading: boolean
552
- isSuccess: boolean
553
- isError: boolean
554
- refetch: () => void
555
- }
556
- ```
557
-
558
- Fetches a service asynchronously and subscribes to invalidation events. When the service is invalidated, it automatically re-fetches.
559
-
560
- ### useSuspenseService
561
-
562
- ```ts
563
- function useSuspenseService<T>(token: ClassType): InstanceType<T>
564
- function useSuspenseService<T, S>(
565
- token: InjectionToken<T, S>,
566
- args: z.input<S>,
567
- ): T
568
- function useSuspenseService<T>(token: InjectionToken<T, undefined>): T
569
- // ... other overloads
570
- ```
571
-
572
- Fetches a service using React Suspense. Throws a promise during loading and the resolved value on success. Subscribes to invalidation events and triggers re-render when the service is invalidated.
573
-
574
- **Note**: Must be used within a `Suspense` boundary and an error boundary.
575
-
576
- ### useOptionalService
577
-
578
- ```ts
579
- function useOptionalService<T>(
580
- token: ClassType,
581
- ): UseOptionalServiceResult<InstanceType<T>>
582
- function useOptionalService<T, S>(
583
- token: InjectionToken<T, S>,
584
- args: z.input<S>,
585
- ): UseOptionalServiceResult<T>
586
- // ... other overloads
587
-
588
- interface UseOptionalServiceResult<T> {
589
- data: T | undefined
590
- error: Error | undefined
591
- isLoading: boolean
592
- isSuccess: boolean
593
- isNotFound: boolean
594
- isError: boolean
595
- refetch: () => void
596
- }
597
- ```
598
-
599
- Loads a service that may not be registered. Returns `isNotFound: true` when the service doesn't exist instead of throwing an error.
600
-
601
- ### useInvalidateInstance
602
-
603
- ```ts
604
- function useInvalidateInstance(): (instance: unknown) => Promise<void>
605
- ```
606
-
607
- Returns a function to invalidate a service instance directly without knowing its token.
608
-
609
- ### useScope
610
-
611
- ```ts
612
- function useScope(): string | null
613
- ```
614
-
615
- Returns the current scope ID. Returns `null` if not inside a `ScopeProvider`.
60
+ `data` is `undefined` until the instance is ready, because a service may initialise asynchronously; when the container already holds the instance, the first render returns it. Create the container once, outside any component, so that it is the same object on every render.
616
61
 
617
- ### useScopeOrThrow
62
+ ## What you get
618
63
 
619
- ```ts
620
- function useScopeOrThrow(): string
621
- ```
622
-
623
- Returns the current scope ID. Throws an error if not inside a `ScopeProvider`.
624
-
625
- ### useScopedContainer
626
-
627
- ```ts
628
- function useScopedContainer(): ScopedContainer | null
629
- ```
630
-
631
- Returns the current `ScopedContainer`. Returns `null` if not inside a `ScopeProvider`.
632
-
633
- ### useScopedContainerOrThrow
634
-
635
- ```ts
636
- function useScopedContainerOrThrow(): ScopedContainer
637
- ```
638
-
639
- Returns the current `ScopedContainer`. Throws an error if not inside a `ScopeProvider`.
640
-
641
- ### useScopeMetadata
642
-
643
- ```ts
644
- function useScopeMetadata<T = unknown>(key: string): T | undefined
645
- ```
646
-
647
- Returns metadata from the current scope. Returns `undefined` if not inside a `ScopeProvider` or if the key doesn't exist.
648
-
649
- ## Troubleshooting
650
-
651
- ### "useContainer must be used within a ContainerProvider"
652
-
653
- Make sure your component is wrapped with `ContainerProvider`:
654
-
655
- ```tsx
656
- <ContainerProvider container={container}>
657
- <YourComponent />
658
- </ContainerProvider>
659
- ```
660
-
661
- ### Service re-fetches on every render
662
-
663
- This usually happens when arguments are not memoized:
664
-
665
- ```tsx
666
- // โŒ Bad - creates new object on every render
667
- const { data } = useService(UserToken, { userId })
668
-
669
- // โœ… Good - stable reference
670
- const args = useMemo(() => ({ userId }), [userId])
671
- const { data } = useService(UserToken, args)
672
- ```
673
-
674
- ### useSuspenseService throws errors
64
+ | Need | How | Docs |
65
+ | ---------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
66
+ | A service with loading and error state | `useService(token)` | [useService](https://navios.tech/docs/di/react/using-services#useservice) |
67
+ | A service through Suspense | `useSuspenseService(token)` | [Suspense](https://navios.tech/docs/di/react/using-services#suspense) |
68
+ | A service that takes arguments | `useService(token, args)`, compared by JSON form | [Services that take arguments](https://navios.tech/docs/di/react/using-services#services-that-take-arguments) |
69
+ | A service that may have no provider | `useOptionalService(token)`, `isNotFound` | [Optional services](https://navios.tech/docs/di/react/using-services#optional-services) |
70
+ | The container in an event handler or an effect | `useContainer()`, `useRootContainer()` | [Outside render](https://navios.tech/docs/di/react/using-services#outside-render) |
71
+ | State per row, modal or tenant | `<ScopeProvider>` with request-scoped services | [ScopeProvider](https://navios.tech/docs/di/react/scopes-and-invalidation#scopeprovider) |
72
+ | The scope's id and metadata | `useScope()`, `useScopeMetadata(key)`, `useScopedContainer()` | [Scope id and metadata](https://navios.tech/docs/di/react/scopes-and-invalidation#scope-id-and-metadata) |
73
+ | Replace an instance and re-render its users | `useInvalidateInstance()`, `container.invalidate()` | [Invalidation](https://navios.tech/docs/di/react/scopes-and-invalidation#invalidation) |
74
+ | Fakes in tests and stories | `new Container({ providers })` given to `ContainerProvider` | [Quick start](https://navios.tech/docs/di/react/#provide-the-container) |
675
75
 
676
- Make sure you've wrapped your component with both `Suspense` and an error boundary:
76
+ Two rules worth knowing before you start: `useSuspenseService` needs an error boundary above it as well as a `Suspense` boundary, and for a request-scoped service that `Suspense` boundary goes inside the `ScopeProvider`, not around it.
677
77
 
678
- ```tsx
679
- <ErrorBoundary>
680
- <Suspense fallback={<Loading />}>
681
- <Component />
682
- </Suspense>
683
- </ErrorBoundary>
684
- ```
685
-
686
- ### Services not invalidating
78
+ ## Changes
687
79
 
688
- When using `useInvalidateInstance`, make sure you have a reference to the service instance:
689
-
690
- ```tsx
691
- // โœ… Good - invalidate the actual instance
692
- const { data: user } = useService(UserService)
693
- const invalidateInstance = useInvalidateInstance()
694
-
695
- const handleRefresh = () => {
696
- if (user) {
697
- invalidateInstance(user)
698
- }
699
- }
700
- ```
80
+ See [CHANGELOG.md](./CHANGELOG.md).
701
81
 
702
82
  ## License
703
83