Using a service

Let's come back to our entry file index.ts.

Our new program will use the PokeApi service and call getPokemon.

Since a service is created from Context it can be treated like a normal Effect inside Effect.gen. We can extract the service API by simply yielding the service itself:

index.ts
import { Effect } from "effect";
import { PokeApi } from "./PokeApi";

const program = Effect.gen(function* () {
  const pokeApi = yield* PokeApi;
});

pokeApi contains all the methods that we defined inside the PokeApi interface.

Again, no need to manually check what methods are available in a service. The IDE does all the work for us
Again, no need to manually check what methods are available in a service. The IDE does all the work for us

We can now call getPokemon:

index.ts
const program = Effect.gen(function* () {
  const pokeApi = yield* PokeApi;
  return yield* pokeApi.getPokemon;
});

Remember that getPokemon is an Effect, therefore we need to use yield* to execute it.

That's a common mistake, pay attention to this!

If you forget yield* you will see the final Effect type containing another Effect. That's because yield* is needed to unwrap the getPokemon effect:

If you notice Effect wrapped inside Effect it's probably because you forgot to yield* somewhere
If you notice Effect wrapped inside Effect it's probably because you forgot to yield* somewhere