Skip to content

Proposal: add subscribe to middlewareAPI #922

Closed
@jonnyreeves

Description

@jonnyreeves

Expand the existing middlewareAPI to include store.subscribe, ie:

var middlewareAPI = {
  getState: store.getState,
  dispatch: (action) => dispatch(action),
  subscribe: store.subscribe
};

Motivation

Stateful middleware implementations wish to observe the store to know when the store' state has been modified and trigger a side-effect; for example - OAuth middleware will detain CALL_API actions when it detects an expired OAuth Grant until the store has been updated with a new, valid Grant:

export function createMiddleware() {
  var detainedActions = [];

  return store => next => action => {
      if (!action[CALL_API]) {
        return next(action);
      }
      if (store.getState().oauthGrant.expired) {
        detainedActions.push(action);
        await obtainNewOauthGrant(store);
        redispatchDetainedActions(store.dispatch);
      } else {
        // ... sign the request.
    }
  }  

  async function obtainNewOauthGrant(store) {
    const unsubscribe = store.subscribe(() => {
      if (!store.getState().oauthGrant.expired) {
        unsubscribe();
        resolve();
      }
    });
    store.dispatch(obtainNewGrant());
  }

  function redispatchDetainedActions(dispatch) {
    // ... redispatch detained actions.
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions