public protocol Middleware

Middleware protocol that represents a suas store middleware A middleware helps extending the dispatch logic of Suas.

A middleware can be used to implement:

  • Logging that logs the state before and after the reducer changes it
  • Perform async network calls and dispatches actions representing the result when the network returns.
  • Other advanced usages…


Implementing a logging middleware.

class LoggerMiddleware: Middleware {
  var api: MiddlewareAPI?
  var next: DispatchFunction?

  func onAction(action: Action, getState: @escaping GetStateFunction, dispatch: @escaping DispatchFunction, next: @escaping NextFunction) {
    // Read the state before any reducer changes it
    print("The old state is \(getState())")

    // Print the action
    print("The action is \(action)")

    // Continue the dispatching process..until the reducer reduces the action
    // Not calling `next` will prevent the action from reaching the reducer

    // Read the state after any reducer changes it
    print("The new state is \(api?.state)")
  • Function called when an action is dispatched



    func onAction(action: Action,



    the dispatched action

    • getState: a function that can be used to read the current Store state
    • dispatch: a function that can be used to dispatch new actions to the Store
    • next: function that represents the continuation of the dispatching process. The middleware can do the following with it:
    • If it calls next the execution will proceed and the action will eventually reach the reducer
    • If it does not call, then the action is said to be handled by the current middleware.
    • Middleware cancall next with a new action, this action is used instead of the original one.