Dependency injection
A Cmd<Msg, E, R> has a third type parameter that has been never on every page so far. R is what the command needs in order to run - and this is the part of Effect that tea-effect gets for free and elm-ts had to emulate with the Reader pattern.
The claim is small and checkable: a command that needs an API client says so in its type, and the program does not compile until something provides one.
Declaring a service
A service is a key plus the shape behind it. Nothing here says how the data is fetched - only what a feature is allowed to ask for:
// A service is a key plus the shape behind it. The key is the type your commands
// will ask for; nothing here says how it is implemented.
export class ApiClient extends Context.Service<
ApiClient,
{
readonly listUsers: Effect.Effect<ReadonlyArray<User>, Http.HttpError>
}
>()('ApiClient') {}Implementing it
// The real implementation: the JSONPlaceholder request from the HTTP guide.
export const ApiClientLive = Layer.succeed(
ApiClient,
ApiClient.of({
listUsers: Http.toTask(listUsers)
})
)That is the real JSONPlaceholder request from the HTTP guide, moved behind the service. The feature no longer knows which request is made or how the client is built - though here it still speaks the transport's error type, because the service's error channel is Http.HttpError. Give the service an error type of its own, and map HttpError into it inside ApiClientLive, if you want the feature independent of the transport as well.
Asking for it
Reaching for the service is an ordinary Effect:
// Asking for the service is an ordinary Effect. The result is a command whose
// `R` says ApiClient - the requirement is now part of the type, and the program
// will not compile until something provides it.
const loadUsers: Cmd.Cmd<Msg, never, ApiClient> = pipe(
Effect.flatMap(ApiClient, (api) => api.listUsers),
Task.attemptWith({
onSuccess: (users: ReadonlyArray<User>): Msg => ({ type: 'UsersReceived', users }),
onFailure: (error: Http.HttpError): Msg => ({ type: 'RequestFailed', error })
})
)Look at the annotation: Cmd.Cmd<Msg, never, ApiClient>. The requirement is now part of the type. You cannot forget it, and you cannot accidentally run this command without an implementation.
update itself is unchanged by any of this:
// `update` itself is untouched by dependency injection: it still just returns a
// command. Only the command's type carries the requirement.
export const update = (
msg: Msg,
model: Model
): readonly [Model, Cmd.Cmd<Msg, never, ApiClient>] => {
switch (msg.type) {
case 'LoadRequested':
return model._tag === 'Loading' ? [model, Cmd.none] : [{ _tag: 'Loading' }, loadUsers]
case 'UsersReceived':
return [{ _tag: 'Loaded', users: msg.users }, Cmd.none]
case 'RequestFailed':
return [{ _tag: 'Failed', error: msg.error }, Cmd.none]
}
}Providing it
Where R gets discharged depends on how you mount the program.
The program owns the root
Provide the layer to the Effect that runs it. (view here is this module's own view function, unchanged by any of this - it is in the full file below.)
// When tea-effect owns the root, provide the layer to the Effect that runs the
// program. `R` is discharged there, and `runPromise` accepts it.
export const main = () => {
const root = createRoot(document.getElementById('app')!)
return Effect.runPromise(
TeaReact.run(TeaReact.program(Users.init, Users.update, view), (dom) =>
root.render(dom)
).pipe(Effect.provide(ApiClientLive))
)
}A program inside a React component
useProgram wants a Context, not a Layer:
// Inside an existing React tree it is `useProgram` instead, and that wants a
// Context rather than a Layer. Build it once, at module level.
const AppRuntime = ManagedRuntime.make(ApiClientLive)
// ApiClientLive is built synchronously, so the context can be too. A layer that
// opens a connection or reads configuration would need `AppRuntime.context()`,
// which is a Promise.
const runtime: Context.Context<ApiClient> = Effect.runSync(AppRuntime.contextEffect)
const useProgram = TeaReact.makeUseProgram(React)
export const UsersFeature = () => {
// Because `R` is not `never`, TypeScript requires the runtime argument here.
// Forgetting it is a compile error, not a failure at runtime.
const { model, dispatch } = useProgram(Users.init, Users.update, () => Sub.none, {
runtime
})
return model._tag === 'Loaded' ? (
<ul>
{model.users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
) : (
<button onClick={() => dispatch({ type: 'LoadRequested' })}>Load</button>
)
}This is the error people hit first
When R is not never, the runtime option is required - the type of useProgram changes shape to demand it. If you see TypeScript complaining about a missing argument on a hook that used to take two, this is why: something in your command tree started requiring a service.
Synchronous versus asynchronous layers
Effect.runSync(AppRuntime.contextEffect) works because Layer.succeed builds synchronously. A layer that opens a connection, reads configuration, or acquires any resource cannot be built that way - use await AppRuntime.context(), which is a Promise, and hold the result in state while it resolves.
The complete file, imports included
import { Context, Effect, ManagedRuntime } from 'effect'
import * as React from 'react'
import { createRoot } from 'react-dom/client'
import * as Sub from 'tea-effect/Sub'
import * as TeaReact from 'tea-effect/React'
import { ApiClient, ApiClientLive } from './ApiClient'
import * as Users from './Users'
const view =
(model: Users.Model): TeaReact.Html<Users.Msg> =>
(dispatch) =>
model._tag === 'Loaded' ? (
<ul>
{model.users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
) : (
<button onClick={() => dispatch({ type: 'LoadRequested' })}>Load</button>
)
// #region whole-app
// When tea-effect owns the root, provide the layer to the Effect that runs the
// program. `R` is discharged there, and `runPromise` accepts it.
export const main = () => {
const root = createRoot(document.getElementById('app')!)
return Effect.runPromise(
TeaReact.run(TeaReact.program(Users.init, Users.update, view), (dom) =>
root.render(dom)
).pipe(Effect.provide(ApiClientLive))
)
}
// #endregion whole-app
// #region hook
// Inside an existing React tree it is `useProgram` instead, and that wants a
// Context rather than a Layer. Build it once, at module level.
const AppRuntime = ManagedRuntime.make(ApiClientLive)
// ApiClientLive is built synchronously, so the context can be too. A layer that
// opens a connection or reads configuration would need `AppRuntime.context()`,
// which is a Promise.
const runtime: Context.Context<ApiClient> = Effect.runSync(AppRuntime.contextEffect)
const useProgram = TeaReact.makeUseProgram(React)
export const UsersFeature = () => {
// Because `R` is not `never`, TypeScript requires the runtime argument here.
// Forgetting it is a compile error, not a failure at runtime.
const { model, dispatch } = useProgram(Users.init, Users.update, () => Sub.none, {
runtime
})
return model._tag === 'Loaded' ? (
<ul>
{model.users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
) : (
<button onClick={() => dispatch({ type: 'LoadRequested' })}>Load</button>
)
}
// #endregion hookWhy this beats a mock
Swapping the implementation is swapping a value:
// A test swaps the implementation and changes nothing else. No mocking library,
// no module interception - the same key, a different value behind it.
export const ApiClientTest = (users: ReadonlyArray<User>) =>
Layer.succeed(
ApiClient,
ApiClient.of({
listUsers: Effect.succeed(users)
})
)No mocking library, no module interception, no reset between tests. The same key, a different value behind it - and the compiler checks that the substitute has the right shape.
Testing uses exactly this layer.
When not to bother
If a command only needs the network and nothing else, Http.send already gives you R = never and there is nothing to inject. Reach for a service when you want the feature to stop knowing where its data comes from - which is usually when you want to test it, or when the same feature has to run against two backends.
Next
- Testing - the payoff.
- Composition -
Rflows up throughCmd.mapunchanged.