### initial Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Result.ts.md Constructs an Initial Result state, which represents a computation that has not yet started or completed. It can optionally be marked as waiting. ```APIDOC ## initial Constructs an Initial Result state, which represents a computation that has not yet started or completed. It can optionally be marked as waiting. **Signature** ```ts export declare const initial: (waiting?: boolean) => Initial ``` Added in v1.0.0 ``` -------------------------------- ### Atom Lifecycle Management Examples Source: https://context7.com/tim-smart/effect-atom/llms.txt Demonstrates lifecycle management for atoms, including keeping atoms alive indefinitely, setting a time-to-live for idle atoms, and reverting to default auto-disposal behavior. ```typescript import { Atom } from "@effect-atom/atom-react" import { Effect } from "effect" // Keep the runtime alive even if no components are mounted const runtimeAtom = Atom.runtime( Effect.succeed("myService").pipe( Effect.map((s) => ({ s })), Effect.toLayer ) ).pipe(Atom.keepAlive) // persists across unmounts // Cache atom value for 5 seconds after last subscriber const cachedAtom = Atom.make(Effect.succeed(42)).pipe( Atom.setIdleTTL("5 seconds") ) // Auto-dispose (default behavior, explicit reset of keepAlive) const disposableAtom = Atom.make(Effect.succeed("temporary")).pipe( Atom.autoDispose ) ``` -------------------------------- ### Create AtomRuntime with Effect Services/Layers Source: https://github.com/tim-smart/effect-atom/blob/main/README.md Shows how to create an `AtomRuntime` from an Effect `Layer`, enabling Atoms to access services defined within that Layer. The example defines a `Users` service and then creates a `runtimeAtom` from its default layer. ```ts import { Atom } from "@effect-atom/atom-react" import { Effect } from "effect" class Users extends Effect.Service()("app/Users", { effect: Effect.gen(function* () { const getAll = Effect.succeed([ { id: "1", name: "Alice" }, { id: "2", name: "Bob" }, { id: "3", name: "Charlie" }, ]) return { getAll } as const }), }) {} // Create a `AtomRuntime` from a `Layer`. // // ┌─── Atom.AtomRuntime // ▼ const runtimeAtom = Atom.runtime(Users.Default) // You can then use the `AtomRuntime` to make Atoms that use the services from the `Layer`. const usersAtom = runtimeAtom.atom( Effect.gen(function* () { const users = yield* Users return yield* users.getAll }), ) ``` -------------------------------- ### Atom.map, Atom.mapResult, Atom.transform Examples Source: https://context7.com/tim-smart/effect-atom/llms.txt Demonstrates how to derive new atoms by transforming values, mapping results, or accessing the full context for complex derivations. Preserves writability if the source atom is writable. ```typescript import { Atom } from "@effect-atom/atom-react" import { Effect } from "effect" const countAtom = Atom.make(5) // Atom.map — plain value transformation // ┌─── Atom.Writable const labelAtom = Atom.map(countAtom, (n) => `Count is ${n}`) // Atom.mapResult — maps only the success value const usersAtom = Atom.make( Effect.succeed([{ id: "1", name: "Alice" }, { id: "2", name: "Bob" }]) ) // ┌─── Atom.Atom> const userCountAtom = Atom.mapResult(usersAtom, (users) => users.length) // Atom.transform — access full Context const enrichedAtom = Atom.transform(usersAtom, (get) => { const result = get(usersAtom) const count = get(countAtom) return { result, count } }) ``` -------------------------------- ### CountClient Tag and Usage Source: https://github.com/tim-smart/effect-atom/blob/main/README.md Demonstrates how to create a special Context.Tag for the HTTP client using AtomHttpApi.Tag and provides examples of its usage in a React component. ```APIDOC ## `CountClient` Tag ### Description Creates a `Context.Tag` for an HTTP client integrated with Effect Atom, providing access to API operations. ### Tag Definition `CountClient` extends `AtomHttpApi.Tag()` ### Configuration - `api`: The `Api` class defining the HTTP endpoints. - `httpClient`: A Layer providing the `HttpClient` (e.g., `FetchHttpClient.layer`). - `baseUrl`: The base URL for the HTTP requests (e.g., `"http://localhost:3000"`). ### Usage in React Component (`SomeComponent`) #### Querying Count - **Hook**: `useAtomValue` - **Operation**: `CountClient.query("counter", "count", { reactivityKeys: ["count"] })` - **Description**: Retrieves the current count. The `reactivityKeys` can be used to invalidate this query. - **Result Handling**: Uses `Result.getOrElse` to display the count or a default value. #### Performing Mutation - **Hook**: `useAtomSet` - **Operation**: `CountClient.mutation("counter", "increment")` - **Description**: Returns a function to trigger the increment mutation. - **Mutation Call**: `increment({ payload: void 0, reactivityKeys: ["count"] })` - `payload`: The data to send with the mutation (void 0 in this case). - `reactivityKeys`: Specifies which queries to invalidate after the mutation completes (e.g., `["count"]`). ``` -------------------------------- ### Define and Use HTTP API Client with Effect-Atom Source: https://github.com/tim-smart/effect-atom/blob/main/README.md Demonstrates defining an HTTP API, creating a client with AtomHttpApi.Tag, and using it within a React component for queries and mutations. Includes setup for FetchHttpClient and a base URL. ```typescript import { AtomHttpApi, Result, useAtomSet, useAtomValue } from "@effect-atom/atom-react" import { FetchHttpClient, HttpApi, HttpApiEndpoint, HttpApiGroup } from "@effect/platform" import { Effect, Schema } from "effect" // Define your api class Api extends HttpApi.make("api").add( HttpApiGroup.make("counter").add( HttpApiEndpoint.get("count", "/count").addSuccess(Schema.Number) ).add( HttpApiEndpoint.post("increment", "/increment") ) ) {} // Use `AtomHttpApi.Tag` to create a special `Context.Tag` that builds the client class CountClient extends AtomHttpApi.Tag()("CountClient", { api: Api, // Provide a Layer that provides the HttpClient httpClient: FetchHttpClient.layer, baseUrl: "http://localhost:3000" }) {} function SomeComponent() { // Use `CountClient.query` for readonly queries const count = useAtomValue(CountClient.query("counter", "count", { // You can register reactivity keys, which can be used to invalidate // the query reactivityKeys: ["count"] })) // Use `CountClient.mutation` for mutations const increment = useAtomSet(CountClient.mutation("counter", "increment")) return (

Count: {Result.getOrElse(count, () => 0)}

) } // Or you can define custom atoms using the `CountClient.runtime` const incrementAtom = CountClient.runtime.fn(Effect.fnUntraced(function*() { const client = yield* CountClient // Use the Tag to access the client yield* client.counter.increment() })) // Or use it in your Effect services class MyService extends Effect.Service()("MyService", { dependencies: [CountClient.layer], // Add the `CountClient` as a dependency scoped: Effect.gen(function*() { const client = yield* CountClient // Use the Tag to access the client const useClient = () => client.counter.increment() return { useClient } as const }) }) {} ``` -------------------------------- ### Add Global Layers to AtomRuntimes Source: https://github.com/tim-smart/effect-atom/blob/main/README.md Provides an example of how to add global Effect Layers to `AtomRuntime`s, which is useful for setting up common services like `Tracer`, `Logger`, or `ConfigProvider` application-wide. ```ts import { Atom } from "@effect-atom/atom-react" import { ConfigProvider, Layer } from "effect" Atom.runtime.addGlobalLayer( Layer.setConfigProvider(ConfigProvider.fromJson(import.meta.env)), ) ``` -------------------------------- ### Context Interface Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md The Context interface provides methods for interacting with Atoms, such as getting their values, subscribing to changes, and managing their lifecycle. ```APIDOC ## Context Interface ### Description Provides methods for interacting with Atoms, including getting values, subscribing to changes, and managing lifecycle. ### Methods - `get
(atom: Atom): A` - `result(atom: Atom>, options?: { readonly suspendOnWaiting?: boolean | undefined }): Effect.Effect` - `resultOnce(atom: Atom>, options?: { readonly suspendOnWaiting?: boolean | undefined }): Effect.Effect` - `once(atom: Atom): A` - `addFinalizer(f: () => void): void` - `mount(atom: Atom): void` - `refresh(atom: Atom): void` - `refreshSelf(): void` - `self(): Option.Option` - `setSelf(a: A): void` - `set(atom: Writable, value: W): void` - `setResult(atom: Writable, W>, value: W): Effect.Effect` - `some(atom: Atom>): Effect.Effect` - `someOnce(atom: Atom>): Effect.Effect` - `stream(atom: Atom, options?: { readonly withoutInitialValue?: boolean; readonly bufferSize?: number }): Stream.Stream` - `streamResult(atom: Atom>, options?: { readonly withoutInitialValue?: boolean; readonly bufferSize?: number }): Stream.Stream` - `subscribe(atom: Atom, f: (_: A) => void, options?: { readonly immediate?: boolean }): void` ### Properties - `readonly registry: Registry.Registry` ``` -------------------------------- ### AtomRegistry Setup and Usage Source: https://context7.com/tim-smart/effect-atom/llms.txt Configure and use the AtomRegistry for managing atom states. Registry.make creates a standalone registry, while RegistryProvider in React scopes it to a component subtree. Registry.layer provides it as a service in Effect programs. ```typescript import { Registry } from "@effect-atom/atom" import { RegistryProvider } from "@effect-atom/atom-react" // Standalone registry (for testing or non-React use) const registry = Registry.make({ defaultIdleTTL: 5000, // ms before idle atoms are disposed timeoutResolution: 100 // ms granularity for TTL checks }) // Inject initial values (e.g. from SSR) const countAtom = Atom.make(0) const registryWithInitialValues = Registry.make({ initialValues: [[countAtom, 99]] }) console.log(registryWithInitialValues.get(countAtom)) // 99 // React: wrap app with RegistryProvider for custom config function App() { return ( ) } // Effect: provide registry as a Layer import { Effect } from "effect" const program = Effect.gen(function* () { const reg = yield* Registry.AtomRegistry return reg.get(countAtom) }) Effect.runPromise(program.pipe(Effect.provide(Registry.layer))) ``` -------------------------------- ### Registry Interface Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Registry.ts.md Defines the core interface for interacting with the Registry, including methods for getting, setting, subscribing, and managing atoms. ```APIDOC ## Registry (interface) ### Description Represents a registry for managing atoms. Provides methods to access, modify, subscribe to, and manage the lifecycle of atoms. ### Interface Definition ```ts export interface Registry { readonly [TypeId]: TypeId readonly getNodes: () => ReadonlyMap | string, Node> readonly get: (atom: Atom.Atom) => A readonly mount: (atom: Atom.Atom) => () => void readonly refresh: (atom: Atom.Atom) => void readonly set: (atom: Atom.Writable, value: W) => void readonly setSerializable: (key: string, encoded: unknown) => void readonly modify: (atom: Atom.Writable, f: (_: R) => [returnValue: A, nextValue: W]) => A readonly update: (atom: Atom.Writable, f: (_: R) => W) => void readonly subscribe: ( atom: Atom.Atom, f: (_: A) => void, options?: { readonly immediate?: boolean } ) => () => void readonly reset: () => void readonly dispose: () => void } ``` ``` -------------------------------- ### get Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md Retrieves the current value of an Atom. ```APIDOC ## get ### Description Retrieves the current value of an Atom. ### Signature ```ts export declare const get: (self: Atom) => Effect.Effect ``` ``` -------------------------------- ### Atom.withFallback Example for Loading States Source: https://context7.com/tim-smart/effect-atom/llms.txt Wraps a Result-typed atom to provide a fallback value while the atom is in its initial loading state. Ensures the UI never shows an 'Initial' state, providing a smoother user experience. ```typescript import { Atom, useAtomValue } from "@effect-atom/atom-react" import { Effect } from "effect" const defaultCountAtom = Atom.make(Effect.succeed(0)) const countAtom = Atom.make( Effect.gen(function* () { yield* Effect.sleep("2 seconds") return 42 }) ).pipe(Atom.withFallback(defaultCountAtom)) // shows 0 while loading function Counter() { const result = useAtomValue(countAtom) // result is never Initial — shows 0 until the real value arrives return
{result._tag === "Success" ? result.value : "…"}
} ``` -------------------------------- ### Create Derived State Atoms Source: https://github.com/tim-smart/effect-atom/blob/main/README.md Shows two methods for creating derived state: using `Atom.make` with a getter function that accesses other Atoms via `get`, and using `Atom.map` for a more direct transformation. ```ts import { Atom } from "@effect-atom/atom-react" const countAtom = Atom.make(0) // You can use the `get` function to get the value of another Atom. // // The type of `get` is `Atom.Context`, which also has a bunch of other methods // on it to manage Atoms. // const doubleCountAtom = Atom.make((get) => get(countAtom) * 2) // You can also use the `Atom.map` function to create a derived Atom. const tripleCountAtom = Atom.map(countAtom, (count) => count * 3) ``` -------------------------------- ### useAtomInitialValues Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom-react/Hooks.ts.md Hook to set initial values for multiple atoms at once. This is useful for initializing the state of several atoms when a component mounts or during application setup. ```APIDOC ## useAtomInitialValues ### Description Initializes multiple atoms with provided values. This hook is typically used once during application setup or component initialization to set the starting state for a collection of atoms. ### Signature ```ts export declare const useAtomInitialValues: (initialValues: Iterable, any]>) => void ``` ``` -------------------------------- ### Atom.debounce Example for Search Input Source: https://context7.com/tim-smart/effect-atom/llms.txt Creates a debounced atom that updates only after the source atom has been stable for a specified duration. Useful for search inputs to avoid excessive updates. ```typescript import { Atom, useAtom } from "@effect-atom/atom-react" const searchInputAtom = Atom.make("") // ┌─── Atom.Writable (updates only after 300ms of silence) const debouncedSearchAtom = Atom.debounce(searchInputAtom, "300 millis") const searchResultsAtom = Atom.make((get) => { const query = get(debouncedSearchAtom) if (!query) return [] return [`Result for: ${query}`] }) function SearchBox() { const [, setSearch] = useAtom(searchInputAtom) return setSearch(e.target.value)} placeholder="Search…" /> } ``` -------------------------------- ### Integrate RPC with AtomRpc.Tag for Typed Queries and Mutations Source: https://context7.com/tim-smart/effect-atom/llms.txt Use AtomRpc.Tag to create a typed RPC client from an RpcGroup. Queries return memoized atoms, and mutations return AtomResultFn. Both support reactivityKeys for cache invalidation. Requires RpcGroup definition and client layer setup. ```typescript import { AtomRpc, useAtomValue, useAtomSet } from "@effect-atom/atom-react" import { Rpc, RpcClient, RpcGroup, RpcSerialization } from "@effect/rpc" import { BrowserSocket } from "@effect/platform-browser" import { Effect, Schema, Layer } from "effect" class ApiRpcs extends RpcGroup.make( Rpc.make("getUsers", { success: Schema.Array(Schema.Struct({ id: Schema.String, name: Schema.String })) }), Rpc.make("createUser", { payload: Schema.Struct({ name: Schema.String }), success: Schema.String }) ) {} class ApiClient extends AtomRpc.Tag()("ApiClient", { group: ApiRpcs, protocol: RpcClient.layerProtocolSocket({ retryTransientErrors: true }).pipe( Layer.provide(BrowserSocket.layerWebSocket("ws://localhost:3000/rpc")), Layer.provide(RpcSerialization.layerJson) ) }) {} function UserList() { const users = useAtomValue( ApiClient.query("getUsers", void 0, { reactivityKeys: ["users"] }) ) const createUser = useAtomSet(ApiClient.mutation("createUser")) return Result.builder(users) .onInitial(() =>

Loading…

) .onError((e) =>

Error: {String(e)}

) .onSuccess((userList) => (
    {userList.map((u) =>
  • {u.name}
  • )}
)) .render() } ``` -------------------------------- ### Result Type and Builder API Source: https://context7.com/tim-smart/effect-atom/llms.txt Demonstrates the Result discriminated union for managing async states and its builder API for type-safe pattern matching in UI rendering. Includes constructors, accessors, combinators, and pattern matching examples. ```typescript import { Result } from "@effect-atom/atom-react" import { Cause, Effect } from "effect" class NotFoundError extends Error { readonly _tag = "NotFoundError" } class NetworkError extends Error { readonly _tag = "NetworkError" } // Constructors const initial = Result.initial() const success = Result.success(42, { waiting: false }) const failure = Result.fail(new NetworkError("timeout")) // Accessors Result.getOrElse(success, () => 0) // => 42 Result.getOrElse(initial, () => 0) // => 0 Result.value(failure) // => Option.none() (no previous) // Combinators const doubled = Result.map(success, (n) => n * 2) const chained = Result.flatMap(success, (n) => Result.success(n + 1)) const combined = Result.all([Result.success(1), Result.success(2)]) // => Result.success([1, 2]) // Pattern matching const ui = Result.match(success, { onInitial: () => "loading", onFailure: (cause) => `error: ${Cause.pretty(cause)}`, onSuccess: (s) => `value: ${s.value}` }) ``` ```typescript // Builder API (for React rendering) const resultAtom = Atom.make( Effect.failCause(Cause.fail(new NotFoundError("not found"))) .pipe(Effect.catchTag("NotFoundError", () => Effect.succeed(0))) ) function DataView({ result }: { result: Result.Result }) { return Result.builder(result) .onInitial(() => Loading…) .onWaiting(() => Refreshing…) .onErrorTag("NotFoundError", (e) => Not found: {e.message}) .onErrorTag("NetworkError", (e) => Network error: {e.message}) .onSuccess((value) => Value: {value}) .render() } ``` -------------------------------- ### make Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Registry.ts.md Constructs a new Registry instance with optional initial values and configuration. ```APIDOC ## make ### Description Factory function to create a new Registry instance. Allows for initial values and configuration of task scheduling and timeouts. ### Method Signature ```ts export declare const make: ( options?: | { readonly initialValues?: Iterable, any]> | undefined readonly scheduleTask?: ((f: () => void) => void) | undefined readonly timeoutResolution?: number | undefined readonly defaultIdleTTL?: number | undefined } | undefined ) => Registry ``` ``` -------------------------------- ### keepAlive Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md Ensures that an atom remains active and does not get garbage collected, returning the same atom. ```APIDOC ## keepAlive **Signature** ```ts export declare const keepAlive:
>(self: A) => A ``` Added in v1.0.0 ``` -------------------------------- ### Get Or Throw Accessor Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Result.ts.md Returns the success value of a Result, throwing an error if the Result is a Failure. ```typescript export declare const getOrThrow: (self: Result) => A ``` -------------------------------- ### Get Cause Accessor Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Result.ts.md Retrieves the 'Cause' from a Result, returning an Option that is None if the Result is not a Failure. ```typescript export declare const cause: (self: Result) => Option.Option> ``` -------------------------------- ### Get Atom Value Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md Retrieves the current value of an atom. This operation is effectful and requires an AtomRegistry. ```typescript export declare const get: (self: Atom) => Effect.Effect ``` -------------------------------- ### Create Atoms with Atom.make Source: https://context7.com/tim-smart/effect-atom/llms.txt Demonstrates various ways to create atoms using Atom.make, including writable atoms, derived atoms, effectful atoms, stream atoms, and scoped atoms. Atoms are lazy and auto-dispose by default. ```typescript import { Atom, Result } from "@effect-atom/atom-react" import { Effect, Stream, Schedule } from "effect" // 1. Writable atom with a plain value const countAtom = Atom.make(0).pipe(Atom.keepAlive) // 2. Derived atom (read-only, re-computes when countAtom changes) const doubleAtom = Atom.make((get) => get(countAtom) * 2) // 3. Effectful atom — value is Result.Result const greetingAtom = Atom.make( Effect.gen(function* () { yield* Effect.sleep("1 second") return "Hello, world!" }) ) // 4. Stream atom — emits latest value as Result.Result const tickAtom = Atom.make(Stream.fromSchedule(Schedule.spaced("1 second"))) // 5. Scoped atom — finalizer runs when atom is rebuilt or disposed const resourceAtom = Atom.make( Effect.gen(function* () { yield* Effect.addFinalizer(() => Effect.log("cleanup")) return "resource" }) ) ``` -------------------------------- ### Get Value Accessor Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Result.ts.md Retrieves the success value from a Result, returning an Option that is None if the Result is not a Success. ```typescript export declare const value: (self: Result) => Option.Option ``` -------------------------------- ### Get Or Else Combinator Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Result.ts.md Provides a default value if the Result is a Failure, otherwise returns the success value. ```typescript export declare const getOrElse: { (orElse: LazyArg): (self: Result) => A | B (self: Result, orElse: LazyArg): A | B } ``` -------------------------------- ### Get Error Accessor Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Result.ts.md Retrieves the error value from a Result, returning an Option that is None if the Result is not a Failure. ```typescript export declare const error: (self: Result) => Option.Option ``` -------------------------------- ### Registry.make / Registry.layer / RegistryProvider Source: https://context7.com/tim-smart/effect-atom/llms.txt Provides utilities for setting up and managing the Atom Registry, which tracks atom values and subscriptions. This includes creating standalone registries, providing them as Effect layers, and setting up React context providers. ```APIDOC ## Registry.make / Registry.layer / RegistryProvider — Registry setup `Registry.make` creates a standalone registry (the engine that tracks atom values and subscriptions). In React, `RegistryProvider` creates a scoped registry for a component subtree. `Registry.layer` provides an `AtomRegistry` service for use in Effect programs. ```ts import { Registry } from "@effect-atom/atom" import { RegistryProvider } from "@effect-atom/atom-react" // Standalone registry (for testing or non-React use) const registry = Registry.make({ defaultIdleTTL: 5000, // ms before idle atoms are disposed timeoutResolution: 100 // ms granularity for TTL checks }) // Inject initial values (e.g. from SSR) const countAtom = Atom.make(0) const registryWithInitialValues = Registry.make({ initialValues: [[countAtom, 99]] }) console.log(registryWithInitialValues.get(countAtom)) // 99 // React: wrap app with RegistryProvider for custom config function App() { return ( ) } // Effect: provide registry as a Layer import { Effect } from "effect" const program = Effect.gen(function* () { const reg = yield* Registry.AtomRegistry return reg.get(countAtom) }) Effect.runPromise(program.pipe(Effect.provide(Registry.layer))) ``` ``` -------------------------------- ### Initial Interface Definition Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Result.ts.md Defines the structure of an Initial Result, representing a computation that has not yet started or completed. ```typescript export interface Initial extends Result.Proto { readonly _tag: "Initial" } ``` -------------------------------- ### layerOptions Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Registry.ts.md Creates a layer for the AtomRegistry with customizable options for initial values and task scheduling. ```APIDOC ## layerOptions ### Description Creates a layer for the AtomRegistry, allowing configuration of initial atom values, task scheduling, and timeouts. ### Method Signature ```ts export declare const layerOptions: (options?: { readonly initialValues?: Iterable, any]> | undefined readonly scheduleTask?: ((f: () => void) => void) | undefined readonly timeoutResolution?: number | undefined readonly defaultIdleTTL?: number | undefined }) => Layer.Layer ``` ``` -------------------------------- ### Custom Atom and Effect Service Usage Source: https://github.com/tim-smart/effect-atom/blob/main/README.md Shows how to define custom atoms using the client runtime and how to integrate the client into Effect services. ```APIDOC ## Custom Atom and Effect Service Integration ### Defining Custom Atoms #### `incrementAtom` - **Description**: A custom atom created using `CountClient.runtime.fn` that encapsulates the logic to increment the counter. - **Implementation**: Uses `Effect.gen` and accesses the `CountClient` to call `client.counter.increment()`. ### Integrating into Effect Services #### `MyService` - **Description**: An example Effect service that depends on and utilizes the `CountClient`. - **Dependencies**: `[CountClient.layer]` - **Scoped Implementation**: Uses `Effect.gen` to access the `CountClient` and defines a `useClient` function that calls `client.counter.increment()`. ``` -------------------------------- ### layer Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Registry.ts.md Provides a live layer for the AtomRegistry, enabling dependency injection of the registry. ```APIDOC ## layer ### Description A live layer that provides the AtomRegistry service, allowing it to be injected into effects. ### Method Signature ```ts export declare const layer: Layer.Layer ``` ``` -------------------------------- ### useAtomValue Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom-react/Hooks.ts.md Hook to get the value of an atom. It can optionally take a mapping function to transform the atom's value before returning it. ```APIDOC ## useAtomValue ### Description Retrieves the current value of an atom. An optional second argument, a mapping function, can be provided to transform the atom's value before it is returned by the hook. ### Signature ```ts export declare const useAtomValue: { (atom: Atom.Atom): A; (atom: Atom.Atom, f: (_: A) => B): B } ``` ``` -------------------------------- ### WriteContext Interface Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md The WriteContext interface provides methods for modifying Atoms, including getting values, refreshing the context, and setting values. ```APIDOC ## WriteContext Interface ### Description Provides methods for modifying Atoms, including getting values, refreshing the context, and setting values. ### Methods - `get(atom: Atom): T` - `refreshSelf(): void` - `setSelf(a: A): void` - `set(atom: Writable, value: W): void` ``` -------------------------------- ### Atom.kvs Source: https://context7.com/tim-smart/effect-atom/llms.txt Creates a writable atom backed by a key-value store, such as `localStorage`. The atom synchronizes with the store by reading on mount and writing on every update. It uses a provided `Schema` for serialization and deserialization. ```APIDOC ## Atom.kvs ### Description Creates a writable atom backed by any `@effect/platform` `KeyValueStore`. The atom automatically reads from the store on mount, writes back on every update, and uses a `Schema` for serialization. ### Usage ```ts import { Atom, useAtom } from "@effect-atom/atom-react" import { BrowserKeyValueStore } from "@effect/platform-browser" import { Schema } from "effect" const kvsRuntime = Atom.runtime(BrowserKeyValueStore.layerLocalStorage) const prefsAtom = Atom.kvs({ runtime: kvsRuntime, key: "user-prefs", schema: Schema.Struct({ theme: Schema.Literal("light", "dark"), fontSize: Schema.Number }), defaultValue: () => ({ theme: "light" as const, fontSize: 14 }) }) function PrefsPanel() { const [prefs, setPrefs] = useAtom(prefsAtom) return ( ) } ``` ``` -------------------------------- ### Counter API Definition Source: https://github.com/tim-smart/effect-atom/blob/main/README.md Defines a sample HTTP API with a 'counter' group containing 'count' (GET) and 'increment' (POST) endpoints. ```APIDOC ## `Api` Class Definition ### Description Defines the structure of the HTTP API, including groups and endpoints. ### Class `Api` ### Methods - `add(group: HttpApiGroup)`: Adds an `HttpApiGroup` to the API. ### Nested Groups #### `counter` (HttpApiGroup) - `add(endpoint: HttpApiEndpoint)`: Adds an `HttpApiEndpoint` to the group. ##### Endpoints within `counter`: 1. **`count` (HttpApiEndpoint)** - **Method**: GET - **Endpoint**: `/count` - **Success Response**: Schema.Number 2. **`increment` (HttpApiEndpoint)** - **Method**: POST - **Endpoint**: `/increment` - **Request Body**: Not specified in source, assumed to be handled by `HttpApiEndpoint.post`. ``` -------------------------------- ### context Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md Creates a runtime factory with a memoization map, used for managing atom contexts. ```APIDOC # constructors ## context **Signature** ```ts export declare const context: (options: { readonly memoMap: Layer.MemoMap }) => RuntimeFactory ``` Added in v1.0.0 ``` -------------------------------- ### Get Atom Result Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md Retrieves the value of an atom that holds a Result type. Optionally suspends if the atom is in a waiting state. Requires an AtomRegistry. ```typescript export declare const getResult: ( self: Atom>, options?: { readonly suspendOnWaiting?: boolean | undefined } ) => Effect.Effect ``` -------------------------------- ### Atom.kvs for Key-Value Store Integration Source: https://context7.com/tim-smart/effect-atom/llms.txt Creates a writable atom backed by a KeyValueStore, automatically reading on mount and writing on update. Uses a Schema for serialization and supports a defaultValue. ```typescript import { Atom, useAtom } from "@effect-atom/atom-react" import { BrowserKeyValueStore } from "@effect/platform-browser" import { Schema } from "effect" const kvsRuntime = Atom.runtime(BrowserKeyValueStore.layerLocalStorage) // ┌─── Atom.Writable<{ theme: "light" | "dark"; fontSize: number }> const prefsAtom = Atom.kvs({ runtime: kvsRuntime, key: "user-prefs", schema: Schema.Struct({ theme: Schema.Literal("light", "dark"), fontSize: Schema.Number }), defaultValue: () => ({ theme: "light" as const, fontSize: 14 }) }) function PrefsPanel() { const [prefs, setPrefs] = useAtom(prefsAtom) return ( ) } ``` -------------------------------- ### useAtomRef Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom-react/Hooks.ts.md Hook to get the current value of a readonly atom reference. This hook is useful for accessing atom state without intending to modify it. ```APIDOC ## useAtomRef ### Description Retrieves the current value of a readonly atom reference (`AtomRef.ReadonlyRef`). This hook is suitable for components that only need to observe atom values. ### Signature ```ts export declare const useAtomRef: (ref: AtomRef.ReadonlyRef) => A ``` ``` -------------------------------- ### `@effect/rpc` Integration Source: https://github.com/tim-smart/effect-atom/blob/main/README.md Utilize `AtomRpc` to create RPC clients for seamless integration with Effect Atom, supporting both queries and mutations. ```APIDOC ## AtomRpc.Tag()(name: string, options: { group: RpcGroup, protocol: Layer }): ClientTag Creates a `Context.Tag` for an RPC client that integrates with Effect Atom. ### Parameters - **name** (string) - The name of the tag. - **options** - Configuration for the RPC client. - **group** (RpcGroup) - The RPC group defining the available methods. - **protocol** (Layer) - A Layer providing the `RpcClient.Protocol`. ## ClientTag.query(method: keyof Group['methods'], payload: any, options?: { reactivityKeys: string[] }): Atom.Atom> Creates an Atom for a read-only RPC query. ### Parameters - **method** (keyof Group['methods']) - The RPC method to call. - **payload** (any) - The payload for the RPC call. - **options** (object, optional) - Configuration options. - **reactivityKeys** (string[]) - Keys to invalidate when the query result is updated. ## ClientTag.mutation(method: keyof Group['methods']) Creates a function for executing RPC mutations. ### Parameters - **method** (keyof Group['methods']) - The RPC method to call. ### Returns A function that takes a payload and optional reactivity keys, and executes the mutation. ## ClientTag.runtime Provides a runtime for creating custom Atoms using the RPC client. ### Example ```ts import { Result, useAtomSet, useAtomValue } from "@effect-atom/atom-react" import { Effect, Layer, Schema } from "effect" import { BrowserSocket } from "@effect/platform-browser" import { Rpc, RpcClient, RpcGroup, RpcSerialization } from "@effect/rpc" class Rpcs extends RpcGroup.make( Rpc.make("increment"), Rpc.make("count", { success: Schema.Number }) ) {} class CountClient extends AtomRpc.Tag()("CountClient", { group: Rpcs, protocol: RpcClient.layerProtocolSocket({ retryTransientErrors: true }).pipe( Layer.provide(BrowserSocket.layerWebSocket("ws://localhost:3000/rpc")), Layer.provide(RpcSerialization.layerJson) ) }) {} function SomeComponent() { const count = useAtomValue(CountClient.query("count", void 0, { reactivityKeys: ["count"] })) const increment = useAtomSet(CountClient.mutation("increment")) return (

Count: {Result.getOrElse(count, () => 0)}

) } const incrementAtom = CountClient.runtime.fn(Effect.fnUntraced(function*() { const client = yield* CountClient yield* client("increment", void 0) })) class MyService extends Effect.Service()("MyService", { dependencies: [CountClient.layer], scoped: Effect.gen(function*() { const client = yield* CountClient const useClient = () => client("increment", void 0) return { useClient } as const }) }) {} ``` ``` -------------------------------- ### kvs Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md Creates a Writable atom that persists its values in a KeyValueStore. It requires a runtime, a key, a schema for serialization, and a default value. ```APIDOC ## kvs ### Description Creates a Writable atom that persists its values in a KeyValueStore. ### Signature ```ts export declare const kvs:
(options: { readonly runtime: AtomRuntime readonly key: string readonly schema: Schema.Schema readonly defaultValue: LazyArg }) => Writable ``` ``` -------------------------------- ### useAtomValue Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom-solid/Hooks.ts.md Hook to get a reactive accessor for an atom's value. It can optionally take a mapping function to transform the atom's value before it's accessed. ```APIDOC ## useAtomValue ### Description Returns a Solid.js accessor for an atom's value. An optional mapping function can be provided to transform the atom's value reactively. ### Signature ```ts export declare const useAtomValue: { (atom: Atom.Atom): Accessor (atom: Atom.Atom, f: (_: A) => B): Accessor } ``` ``` -------------------------------- ### Get Server Value of an Atom Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md The `getServerValue` function retrieves the server-specific value of an atom, provided a `Registry` is available. This is useful for server-side rendering or specific server-only logic. ```typescript export declare const getServerValue: { (registry: Registry.Registry): (self: Atom) => A; (self: Atom, registry: Registry.Registry): A } ``` -------------------------------- ### make constructor Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/AtomRef.ts.md Creates a new AtomRef, which is a reference to a piece of state that can be read and updated. ```APIDOC ## make ### Description Creates a new AtomRef, which is a reference to a piece of state that can be read and updated. ### Signature ```ts export declare const make: (value: A) => AtomRef ``` ``` -------------------------------- ### useAtomRefPropValue Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom-react/Hooks.ts.md Hook to get the value of a specific property from an atom reference. Similar to `useAtomRefProp` but directly returns the property's value instead of another atom reference. ```APIDOC ## useAtomRefPropValue ### Description Retrieves the current value of a specific property from an atom reference. This hook provides direct access to a nested value without returning a new atom reference, useful for simple value consumption. ### Signature ```ts export declare const useAtomRefPropValue: (ref: AtomRef.AtomRef, prop: K) => A[K] ``` ``` -------------------------------- ### Registry layer with options Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Registry.ts.md Creates a Layer for the AtomRegistry with customizable options, including initial values, task scheduling, timeout resolution, and default idle TTL. ```typescript export declare const layerOptions: (options?: { readonly initialValues?: Iterable, any]> | undefined readonly scheduleTask?: ((f: () => void) => void) | undefined readonly timeoutResolution?: number | undefined readonly defaultIdleTTL?: number | undefined }) => Layer.Layer ``` -------------------------------- ### AtomRuntime Interface Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md The AtomRuntime interface defines the core methods for creating and interacting with reactive atoms. It includes methods for creating atoms from effects, streams, functions, and for managing subscriptions. ```APIDOC ## AtomRuntime (interface) Added in v1.0.0 ### Methods - **atom**: Creates an Atom from an Effect or Stream. - Overloads for creating from `(get: Context) => Effect` or `Effect`. - Overloads for creating from `(get: Context) => Stream` or `Stream`. - Options include `initialValue`. - **fn**: Creates a reactive function that returns an Atom. - Supports creating from `(arg: Arg, get: FnContext) => Effect` or `(arg: Arg, get: FnContext) => Stream`. - Options include `initialValue`, `reactivityKeys`, and `concurrent`. - **pull**: Creates a writable Atom from a Stream, with options for accumulation and initial value. - **subscriptionRef**: Creates a writable Atom from a SubscriptionRef, which can be created from an Effect. - **subscribable**: Creates an Atom from a Subscribable, which can be created from an Effect. ``` -------------------------------- ### make Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom-react/ScopedAtom.ts.md Creates a ScopedAtom instance. It accepts a factory function that either takes no arguments or an input value to produce an Atom. ```APIDOC ## make ### Description Creates a ScopedAtom instance. It accepts a factory function that either takes no arguments or an input value to produce an Atom. ### Signature ```ts export declare const make: , Input = never>( f: (() => A) | ((input: Input) => A) ) => ScopedAtom ``` ``` -------------------------------- ### useAtomRefPropValue Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom-solid/Hooks.ts.md Hook to get a reactive accessor for a specific property of an atom ref. This allows components to reactively read nested properties without needing to update the entire atom ref. ```APIDOC ## useAtomRefPropValue ### Description Provides a reactive accessor for a specific property of an atom ref. This hook allows components to subscribe to changes in nested properties of an atom. ### Signature ```ts export declare const useAtomRefPropValue: (ref: AtomRef.AtomRef, prop: K) => Accessor ``` ``` -------------------------------- ### initialValue Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/Atom.ts.md Provides an initial value for an atom, returning the atom and its initial value. Supports two overloaded signatures for convenience. ```APIDOC ## initialValue **Signature** ```ts export declare const initialValue: { (initialValue: A): (self: Atom) => readonly [Atom, A] (self: Atom, initialValue: A): readonly [Atom, A] } ``` Added in v1.0.0 ``` -------------------------------- ### Collection Interface Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom/AtomRef.ts.md The Collection interface extends ReadonlyRef and manages an array of AtomRefs. It offers methods like `push`, `insertAt`, and `remove` for modifying the collection, and `toArray` to get the current values. ```typescript export interface Collection extends ReadonlyRef>> { readonly push: (item: A) => Collection readonly insertAt: (index: number, item: A) => Collection readonly remove: (ref: AtomRef) => Collection readonly toArray: () => Array } ``` -------------------------------- ### defaultRegistry Source: https://github.com/tim-smart/effect-atom/blob/main/docs/atom-vue/index.ts.md The default registry instance provided by the library. ```APIDOC ## defaultRegistry ### Description The default registry instance. ### Signature ```ts export declare const defaultRegistry: Registry.Registry ``` ``` -------------------------------- ### Create Atoms with Scoped Effects and Finalizers Source: https://github.com/tim-smart/effect-atom/blob/main/README.md Demonstrates creating an Atom with an Effect that includes a finalizer. This finalizer will be executed when the Atom is no longer needed or is rebuilt, ensuring resource cleanup. ```ts import { Atom } from "@effect-atom/atom-react" import { Effect } from "effect" const resultAtom = Atom.make( Effect.gen(function* () { // Add a finalizer to the `Scope` for this Atom // It will run when the Atom is rebuilt or no longer needed yield* Effect.addFinalizer(() => Effect.log("finalizer")) return "hello" }), ) ```