@navios/di-react 1.0.0-alpha.3 → 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 +21 -0
- package/README.md +45 -665
- package/lib/{index.js → index.cjs} +249 -255
- 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 -255
- package/lib/index.mjs.map +1 -1
- package/package.json +32 -18
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -87
- package/coverage/clover.xml +0 -270
- package/coverage/coverage-final.json +0 -10
- package/coverage/favicon.png +0 -0
- package/coverage/hooks/index.html +0 -191
- package/coverage/hooks/use-container.mts.html +0 -268
- package/coverage/hooks/use-invalidate.mts.html +0 -208
- package/coverage/hooks/use-optional-service.mts.html +0 -910
- package/coverage/hooks/use-scope.mts.html +0 -346
- package/coverage/hooks/use-service.mts.html +0 -760
- package/coverage/hooks/use-suspense-service.mts.html +0 -784
- package/coverage/index.html +0 -131
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/providers/container-provider.mts.html +0 -139
- package/coverage/providers/context.mts.html +0 -130
- package/coverage/providers/index.html +0 -146
- package/coverage/providers/scope-provider.mts.html +0 -355
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -210
- 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 -143
- 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-scope.spec.mts +0 -293
- 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 -275
- package/src/hooks/use-scope.mts +0 -87
- package/src/hooks/use-service.mts +0 -225
- package/src/hooks/use-suspense-service.mts +0 -233
- 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/README.md
CHANGED
|
@@ -1,703 +1,83 @@
|
|
|
1
1
|
# @navios/di-react
|
|
2
2
|
|
|
3
|
-
React
|
|
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
|
-
|
|
5
|
+
**[Documentation](https://navios.tech/docs/di/react/)** · [API reference](https://navios.tech/docs/di/reference/react-api)
|
|
6
6
|
|
|
7
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
312
|
-
|
|
313
|
-
|
|
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
|
-
|
|
359
|
-
|
|
360
|
-
Get the current `ScopedContainer`, throwing an error if not inside a `ScopeProvider`.
|
|
31
|
+
const container = new Container()
|
|
361
32
|
|
|
362
|
-
|
|
363
|
-
|
|
33
|
+
function Greeting({ name }: { name: string }) {
|
|
34
|
+
const { data: greetings, error } = useService(GreetingService)
|
|
364
35
|
|
|
365
|
-
|
|
366
|
-
|
|
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 <
|
|
39
|
+
return <p>{greetings.greet(name)}</p>
|
|
370
40
|
}
|
|
371
|
-
```
|
|
372
41
|
|
|
373
|
-
|
|
42
|
+
function SuspendingGreeting({ name }: { name: string }) {
|
|
43
|
+
const greetings = useSuspenseService(GreetingService)
|
|
374
44
|
|
|
375
|
-
|
|
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
|
-
<
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
</
|
|
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
|
-
|
|
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
|
-
|
|
62
|
+
## What you get
|
|
618
63
|
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
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
|
-
|
|
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
|
-
|
|
679
|
-
<ErrorBoundary>
|
|
680
|
-
<Suspense fallback={<Loading />}>
|
|
681
|
-
<Component />
|
|
682
|
-
</Suspense>
|
|
683
|
-
</ErrorBoundary>
|
|
684
|
-
```
|
|
685
|
-
|
|
686
|
-
### Services not invalidating
|
|
78
|
+
## Changes
|
|
687
79
|
|
|
688
|
-
|
|
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
|
|