Options
All
  • Public
  • Public/Protected
  • All
Menu

stately-async

[api] [github]
npm

This module contains types and functions for representing and managing the state of asynchronous operations. It is the underlying data API behind the <Async> component in stately-react.

All asynchronous tasks have a similar lifecycle: they are called, data is emitted once or multiple times, and either the task is completed or an error is encountered. Typically, the code to manage this lifecycle is duplicated for every asynchronous action, whether it is done with epics, sagas, or component lifecycle.

This module provides functions and types that allow a consumer to use self-managing stateful "lifecycles" for arbitrary asynchronous tasks. A lifecycle can be created for any asynchronous function, regardless of its parameter arity, output type, or underlying implementation.

It is implemented following the action/reducer pattern, and is intended to work with Redux or any other state managment system that uses actions and reducers (such as <Controllable> components.)

Usage

Most asynchronous operations can be expressed declaratively using the <Async> component, which is preferable to using this library directly. However, unusual or custom use cases may arise where it is ideal to create and use an AsyncLifecycle directly:

import store from './myStore'
import getTweets from './getTweets'
import { asyncLifecycle } from 'stately-async'

class TweetsComponent extends React.Component {
  constructor(props) {
    super(props)
    this.tweetsLifecycle = asyncLifecycle(getTweets)
  }

  render() {
    const { state } = this.props
    return state.data ? <TweetsView tweets={state.data} />
      : state.error ? <ErrorMessage error={state.error}>
      : state.status === 'active' ? <LoadingSpinner />
      : null
  }

  componentDidMount() {
    store.dispatch(this.tweetsLifecycle.call('@myTwitterHandle'))
  }

  componentDidUnmount() {
    store.dispatch(this.tweetsLifecylce.destroy())
  }
}

Index

Type aliases

AsyncGenerator

AsyncGenerator: function

A function that returns an AsyncIterable. Generally, these are defined using async function*.

Type declaration

    • (...params: Params): AsyncIterable<Data>
    • Parameters

      • Rest ...params: Params

      Returns AsyncIterable<Data>

AsyncOperation

AsyncOperation: ObservableInputFunction<Data, Params> | AsyncGenerator<Data, Params>

A type describing any function that returns a value that can be represented with an Observable (which is virtually anything). This type is used as the constraint for the sole parameter of asyncLifecycle.

AsyncPhase

AsyncPhase: "call" | "data" | "error" | "complete" | "destroy"

A union type representing all of the possible suffix values for {@link AsyncAction#type}.

AsyncState

AsyncState: InitialAsyncState | ActiveAsyncState<Data, Params> | ErrorAsyncState<Data, Params> | CompletedAsyncState<Data, Params>

The union type describing all possible states of an AsyncState. The possible types for each field vary depending on status. When collapsed, the type looks like:

type AsyncState<Data, Params> = {
  status: null | 'active' | 'error' | 'completed'
  params: null | Params
  data: null | Data
  error: null | unknown
}

Note that the type of error is unknown when it is not null. That is because, in JavaScript, a throw statement can throw a value of any type. As such, the type of error cannot be inferred. It must be narrowed using type guards before it can be used.

AsyncStateStatus

AsyncStateStatus: null | "active" | "error" | "completed"

The possible values for {@link AsyncState#status}.

ObservableFunction

ObservableFunction: function

A function that returns an Observable.

Type declaration

    • (params: Params): Observable<Data>
    • Parameters

      • params: Params

      Returns Observable<Data>

ObservableInputFunction

ObservableInputFunction: function

A function that returns anything that can be converted to an Observable.

Type declaration

    • (...params: Params): ObservableInput<Data>
    • Parameters

      • Rest ...params: Params

      Returns ObservableInput<Data>

Omit

Omit: Pick<T, Exclude<keyof T, K>>

RegisterListener

RegisterListener: function

Signature of an event-like API for subscribing to Redux Actions. Used internally as a testing utility.

Type declaration

    • (match: function, handler: function, onError?: undefined | function): Unsubscribe
    • Parameters

      • match: function
          • (action: E): boolean
          • Parameters

            • action: E

            Returns boolean

      • handler: function
          • (action: E): void
          • Parameters

            • action: E

            Returns void

      • Optional onError: undefined | function

      Returns Unsubscribe

Subtract

Subtract: Omit<T, keyof K>

Unsubscribe

Unsubscribe: function

Type declaration

    • (): void
    • Returns void

Variables

Const ACTION_PREFIX

ACTION_PREFIX: "async" = "async"

The type prefix applied to every AsyncAction.

Const StatelyAsyncSymbol

StatelyAsyncSymbol: unique symbol = Symbol('stately-async')

Symbol used as a namespace for stately-async data on public objects.

Const asyncStateReducer

asyncStateReducer: function = chain(callReducer, dataReducer, errorReducer, completeReducer)

A reducer that handles AsyncActions and updates the corresponding AsyncState. It is called by statelyAsyncReducer. Generally, you should not have to use this reducer directly.

Type declaration

    • (state: S | undefined, action: A): S
    • Parameters

      • state: S | undefined
      • action: A

      Returns S

Const byUuid

byUuid: Cache

Const initialAsyncState

initialAsyncState: InitialAsyncState = Object.freeze({status: null,params: null,data: null,error: null,}) as InitialAsyncState

Functions

Const $from

  • $from<Item>(observableInput: AsyncIterable<Item> | ObservableInput<Item>): SubjectLike<any, any> | Observable<Item>

Const $fromAsyncIterable

  • $fromAsyncIterable<Data>(asyncIterable: AsyncIterable<Data>): Observable<Data>
  • Internal. Converts an AsyncIterable to an Observable by piping its yield into the subscriber until the AsyncIterable is exhausted.

    Type parameters

    • Data

    Parameters

    • asyncIterable: AsyncIterable<Data>

    Returns Observable<Data>

Const $fromStore

Const $toEvents

  • $toEvents(action$: Observable<Action>): EventAPI<Action>
  • Given an Observable<Action>, returns a simple event-like API that can be used to register simple "handlers" for Redux actions. Once registered, a handler will be called with the dispatched action(s) matching the given filter. The optional onError parameter is called if an exception is thrown at any time, creating an error boundary to prevent cryptic failures. Intended only as a utility for testing middleware. Do not use this in production.

    Tip: Passing a Mocha.Done callback as the onError parameter will cause an exception thrown in the handler to fail the current test. This way, this function can be used to make assertions about store state or component output based on an expected action.

    See observables.spec.ts for an example.

    Parameters

    • action$: Observable<Action>

    Returns EventAPI<Action>

Const $toMiddleware

  • $toMiddleware(action$: Subject<Action>): Middleware
  • Returns a Redux Middleware that pipes all dispatched actions through the given Subject. Essentially, provides an indirect means to create an Observable<Action> from a Redux store. Subscribers to the Subject are notified after the reducers are called, so can perform side-effects without delaying state updates. This middleware can be used as a lightweight alternative to redux-observable.

    Parameters

    • action$: Subject<Action>

    Returns Middleware

Const asyncActionCreatorFactory

  • asyncActionCreatorFactory<Data, Params>(operation: AsyncOperation<Data, Params>, id: string): (Anonymous function)
  • Internal factory function that builds an AsyncActionCreator with the given lifecycle metadata and AsyncPhase.

    The function defines how AsyncActions are created:

    • how the action "type" strings are generated
    • how an action payload is packaged
    • how the lifecycle metadata is packaged

    This information is useful to anyone who intends to define custom handling for AsyncActions, such as:

    • creating a custom reducer to update other parts of the state tree (keeping a historical record of requests?)
    • creating a custom Epic, Saga, or other middleware to create side-effect sequences (chain several AsyncFunctions serially?)

    The public function asyncActionMatcher can be used by reducers or middleware to recognize and filter AsyncActions.

    Type parameters

    • Data

    • Params: any[]

    Parameters

    Returns (Anonymous function)

asyncActionMatcher

  • asyncActionMatcher<Data, Params>(operation: AsyncOperation<Data, Params> | undefined, phase: "call"): function
  • asyncActionMatcher<Data, Params>(operation: AsyncOperation<Data, Params> | undefined, phase: "data"): function
  • asyncActionMatcher<Data, Params>(operation: AsyncOperation<Data, Params> | undefined, phase: "error"): function
  • asyncActionMatcher<Data, Params>(operation?: AsyncOperation<Data, Params>, phase?: AsyncPhase): function
  • Factory that creates a configurable type guard for filtering and differentiating AsyncActions.

    This function is useful to anyone who intends to define custom handling for AsyncActions, such as:

    • creating a custom reducer to update other parts of the state tree (keeping a historical record of requests?)
    • creating a custom Epic, Saga, or other middleware to create asynchronous operation sequences (chain several AsyncFunctions serially?)

    The returned guard will test a given action, returning true iff:

    • the action is an AsyncAction
    • no type is given, or the action's saction matches the given type
    • no operation is given, or the action's infix matches the name of the given operation

    See {@link createSessionActionCreator} for information about the internal structure of AsyncActions.

    Type parameters

    • Data

    • Params: any[]

    Parameters

    Returns function

      • (action: Action): boolean
      • Parameters

        • action: Action

        Returns boolean

  • Type parameters

    • Data

    • Params: any[]

    Parameters

    Returns function

      • (action: Action): boolean
      • Parameters

        • action: Action

        Returns boolean

  • Type parameters

    • Data

    • Params: any[]

    Parameters

    Returns function

      • (action: Action): boolean
      • Parameters

        • action: Action

        Returns boolean

  • Type parameters

    • Data

    • Params: any[]

    Parameters

    Returns function

      • (action: Action): boolean
      • Parameters

        • action: Action

        Returns boolean

Const asyncLifecycle

Const callReducer

Const completeReducer

Const dataReducer

Const errorReducer

Const get

Const getOperationName

  • getOperationName<Data, Params>(asyncOperation: AsyncOperation<Data, Params>, id: string): string

Const isAsyncAction

  • isAsyncAction(action: Action): boolean

Const isAsyncIterable

  • isAsyncIterable<Data>(obj: AsyncIterable<Data> | any): boolean

Const isStoreLike

  • isStoreLike(maybeStoreLike: StoreLike<any, any> | any): boolean

Const remove

  • remove(uuid: string): void

Const set

  • set<Data, Params>(uuid: string, lifecycle: AsyncLifecycle<Data, Params>): void

Const statelyAsyncEpic

  • statelyAsyncEpic(action$: Observable<Action>): Observable<Action>
  • Accepts an Observable<Action> and subscribes to it. When an AsyncAction of type call is received, the epic triggers the corresponding AsyncOperation.

    When the AsyncOperation emits data, encounters an error, or is completed, the 'data', 'error', and 'complete' actions are dispatched, respectively.

    The function signature matches the Epic type from redux-observable, and is meant to be used with combineEpics if you are using redux-observable in your project. If you are not using redux-observable, use statelyAsyncMiddleware instead.

    Parameters

    • action$: Observable<Action>

    Returns Observable<Action>

Const statelyAsyncMiddleware

  • statelyAsyncMiddleware(store: MiddlewareAPI<Dispatch<AnyAction>, any>): function
  • Lightweight integration middleware, intended for projects that are not using redux-observable. Serves as a direct store integration for statelyAsyncEpic.

    Parameters

    • store: MiddlewareAPI<Dispatch<AnyAction>, any>

    Returns function

      • (next: Dispatch<AnyAction>): function
      • Parameters

        • next: Dispatch<AnyAction>

        Returns function

          • (action: any): any
          • Parameters

            • action: any

            Returns any

Const statelyAsyncReducer

Legend

  • Module
  • Object literal
  • Variable
  • Function
  • Function with type parameter
  • Index signature
  • Type alias
  • Enumeration
  • Enumeration member
  • Property
  • Method
  • Interface
  • Interface with type parameter
  • Constructor
  • Property
  • Method
  • Index signature
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Method
  • Accessor
  • Index signature
  • Inherited constructor
  • Inherited property
  • Inherited method
  • Inherited accessor
  • Protected property
  • Protected method
  • Protected accessor
  • Private property
  • Private method
  • Private accessor
  • Static property
  • Static method

Generated using TypeDoc