Storing The Last Dispatched Action In Aurelia Store

Another day, another Aurelia Store tip/hack. Recently, I encountered an interesting situation where I wanted to know when a specific action has fired, being able to check for it within my state subscriptions.

Now, it is highly likely there is a better way to do this. RxJS is quite magical and has a seemingly bottomless trove of treasures and ways to work with observables and data.

The use case is simple. Inside of my subscriptions, I want to know if a specific action has fired and in some cases, what the parameters for said action were. I decided this was the perfect use case for an Aurelia Store middleware.

function lastCalledActionMiddleware(state: State, originalState: State, settings = {}, action: CallingAction) {
    state.$action = {
        name: action.name,
        params: action.params ?? {}
    };

    return state;
}

This is the middleware function and registration. It sets a property defined in your state called $action which stores the currently fired action passing through the middleware as well as the parameters supplied. I prefix with a $ to make the chances of it being overwritten elsewhere highly unlikely.

When registering the middleware, I only want to know when it has fired. So, I choose to place it after.

this.store.registerMiddleware(lastCalledActionMiddleware, MiddlewarePlacement.After);

As you can see below in Redux Developer Tools, my property is being stored and the parameters supplied to the dispatched action.

If you know of a better way to do this, I would love to hear about it. For my use cases, this works quite well and fine. A middleware seems like the perfect use case for something like this.

Leave a Reply

Your email address will not be published. Required fields are marked *