Subscriptions

When you implement the environment interface it is encouraged to use actions to signal resolved requests.

circle-exclamation

An example of this would be.

import { Subscription } from 'react-states'

type ApiAction =
  | {
    type: 'API:FETCH_SANDBOX_SUCCESS'
    id: string
    sandbox: SandboxDTO
  }
  | {
    type: 'API:FETCH_SANDBOX_ERROR'
    id: string
    error: string
  }

export type Api = {
  subscription: Subscription<ApiAction>
  /**
  * @fires API:FETCH_SANDBOX_SUCCESS
  * @fires API:FETCH_SANDBOX_ERROR
  */
  fetchSandbox(id: string): void
}

Now we are not returning anything, but calling fetchSandbox will result in one of two actions. Doing this does not only comply better with Reacts behaviour, but gives several other benefits:

  • Features does not have to translate the result of the Promise into an action, all actions from the subscription is passed into the feature to possibly be handled

  • Environment effects can emit actions synchronously and asynchronously

  • Environment effects can emit multiple actions. This can be related to caching, lazy updating and/or automatically subscribing to the data

  • You get typed errors

  • Tests no longer needs to run asynchronously as the responses can be triggered as synchronous actions

There are many opportunities to optimize how effects deals with over fetching, caching etc.

Prevent unnecessary requests

Only do a single fetch for any item requested at any time.

Caching reads

You can keep the result to optimistically return the cache, while lazily loading the latest version.

Read subscriptions

If you are able to subscribe to the data you read, that can be integrated with any read.

Last updated

Was this helpful?