Dependable React
Getting started
Note: dependable-react
has a peer dependency to react@^16.8.0
, so don't forget to install the latest React version:
npm install --save dependable-react react react-dom
Usage
DefineModule
Use this to setup your services/tokens/factories/... that will later be injected. Take care that you can't inject anything before defining it. You can define:
- A class (that will be a singleton when injected)
- A value (e.g.
window
) - A factory (method that will be called)
You can also define a parent scope to enable scope nesting.
;
DefineModule;
InjectionProvider
A provider that creates a new scope and passes it to the useInject
automatically. This enables structural scoping without worying about the scope tokens.
;
;
GenerateTestBed
When testing your code that depends on something (e.g. DataService
) you can't use DefineModule
since it's a global thing. Use GenerateTestBead
in a beforeEach
hook.
;
; ; beforeEach;
InjectionToken
If for some reason you don't want to use the exact dependency for storing the value (e.g. window
) you can use InjectionToken
instead.
new InjectionTokenkey: string;
; DefineModule;
inject
Use this for injecting stuff in non-react code.
;
⚠️Note: ⚠️ Take care when defining modules to define them in the order of injection. The previous exapmle would only work as this:
DefineModule;
useInject
;
Scope & SSR support
In order to support Server-side rendering and other use cases that require multiple scopes, there is a possibility to define a specific scope.
The scope will be passed to the class as the constructor argument or to a factory as a function argument. That way the class or factory can pass it to inject if they need it.
useContextInject
;
To make things simpler with React, the most likely case is to pass the scope through the React context. To avoid two operations (useContext
to get the scope, and then useInject
), there is one more react hook called useContextInject
.
TODO
Polyfilling
The lib makes use of the following features that are not yet available everywhere. Based on your browser support, you might want to polyfill them:
License
The MIT License
Credits
dependable-react is maintained and sponsored by Infinum.
