TypeScript and Object.Entries

If you are using a dictionary or map in TypeScript you may want to know how many elements are mapped. This can be done with Object.Entries(myMappedObject).length. However, the default Typescript configuration won’t let use this latest function because it’s only available in EcmaScript 2017. To get access to it, you need to change the tsconfig.json. Tsconfig.json has a portion called “lib” which increments TypeScript with libraries. To have access to Object.Entries, you need to add “es2017.object”.

    "lib": [
      "es6",
      "dom",
      "es2017.object" 
    ]

If you are curious about the TypeScript generic way to have a dictionary, you can use this interface:

export interface MyMap<T> {
    [id: string]: T;
}

From there you can do:

const c: MyMap<MyObject> = {};
c["myId1"] = myObject1;
c["myId2"] = myObject2;
c["myId3"] = myObject3;
const numberOfElementInDictionary = Object.entries(c).length;

New Book Released

As every year since the last five years, I am compiling all relevant blog articles I wrote during the year, format and review all of them and send them to be proofread by someone way better than me! This year, I was able to accomplish it few weeks before Christmas. It is available right now on Amazon and will be available in few days for Kindle.



For the curious, the picture of the front page is a picture I took while visiting Stanford University this year.

The first four volumes were more around Microsoft Asp.Net in enterprises. This one focuses on TypeScript and React. Here are some subjects discussed in the book: New features about TypeScript, differences between Flow and TypeScript, migrating AngularJs to React, processing images with NodeJs, flux cycle with React and Redux, Redux middleware, configuring Gulp and Webpack for TypeScript, NPM, webworker, building performance with TypeScript, Rest and destructor operators, multitudes of JavaScript sort algorithms.

How to Have A Hook Before a Redux Store Notify its Subscriber with TypeScript

This is a long title but it says all. Redux is well known to function calling other functions with the capability of getting into the pipeline easily. For example, it’s a defined pattern to create a middleware if you want to inject some code in the pipeline between the time an action is dispatched and that the store consumes the action. But, let say you want to hook some code between the store and the time it notifies everyone listening to the store, how would you do it?

Before getting into details, let’s just summarize the difference between a middleware and what we try to accomplish. The middleware pattern is an upfront hook and is a type of store enhancer that Redux support by default. It’s useful to handle a specific scenario where the middleware looks for specific data in the action and do something on expected type or payload. It’s useful as well when we want to do a general action. In both cases, it’s before the data is intercepted by reducers. The other scenario to hook before the notification is also done with Redux Enhancer. This time, a reducer modify the Redux store (main state) and the store is ready to notify all its subscriber to have the UI to get refreshed. With Redux, all subscribers are the one who used “connect” for example or manually used the “subscribe” function. If you used the “connect” approaches, the function “mapStateToProp” will be called and the React component that is connected will receive the new value. The Redux Enhancer allows you to do custom logic around the store like between the notification and the mapping occurs.

You may still think about why would you like to have something that far in the pipeline. One scenario may be that you have a middleware that was normalizing all the data and dispatching different part. Multiple reducers may require storing the data in different places. Since many reducers may be called, multiple notifications may also be triggered with the consequence of having many mapping to be called and many UI refreshes. While the UI portion may be handled with React logic (shouldUpdateComponent) to reduce potential performance penalty, the mapping code is still invoked. The issue around the mapping is that if you are normalizing your data, it would be the place to denormalize and hence not yet having all the data in the store to denormalized — you want to denormalize only once your normalizer middleware is done dispatching ALL the data to ALL reducers. This is where a Redux enhancer can be helpful. The solution is to have a normalizerMiddleware and a Redux enhancer that will only allow the store to trigger notifications if not in a batch of dispatch. The normalizer middleware will be the one scoping the all the dispatches functions and will tell to the Redux’s enhancer to notify. As you will see, the pattern will not block any notification if the middleware is not explicitly mentioning that we enter a phase of batching. This is important for all other scenarios that don’t require batching notification.

import { StoreEnhancer, StoreEnhancerStoreCreator, Reducer, Store, Dispatch, Unsubscribe } from "redux";

export function batchedSubscribeEnhancer<S>(hook: (notify: () => void, store: Store<S>) => void): StoreEnhancer<S> {

    let currentListeners: (() => void)[] = []; 
    let nextListeners: (() => void)[] = currentListeners; 

    function ensureCanMutateNextListeners(): void {
        if (nextListeners === currentListeners) {
            nextListeners = currentListeners.slice();
        }
    }

    function subscribe(listener: () => void): Unsubscribe {
        let isSubscribed = true;

        ensureCanMutateNextListeners();
        nextListeners.push(listener);

        return function unsubscribe(): void {
            if (!isSubscribed) {
                return;
            }

            isSubscribed = false;

            ensureCanMutateNextListeners();
            const index = nextListeners.indexOf(listener);
            nextListeners.splice(index, 1);
        };
    }

    function notifyListeners(): void {
        const listeners = currentListeners = nextListeners;
        for (let i = 0; i < listeners.length; i++) {
            listeners[i]();
        }
    }

    return (next: StoreEnhancerStoreCreator<S>): StoreEnhancerStoreCreator<S> =>
        (reducer: Reducer<S>, preloadedState?: S): Store<S> => {
            const store = next(reducer);
            function dispatch(dispatchArgs: Dispatch<S>): Dispatch<S> {
                const dispatchResult: Dispatch<S> = store.dispatch(dispatchArgs);
                hook(notifyListeners, store);
                return dispatchResult;
            }

            // Store<S>
            return {
                ...store,
                dispatch,
                subscribe
            };
        };
}

The code is the enhancer that will be injected in the configuration. It was inspired by the Redux Batch Subscribe. Some differences are that this is in TypeScript and that it is built to work with access to the store to take a decision about when to notify.

The following code shows how to setup the Redux’s enhancer. Normally, you’ll have many middlewares, some reducers and when it’s time to setup your store you need to call for your enhancer. As you can see in the example below, we use the store to get a particular state we stored during the middleware phase to ensure we are in “batch mode”. When we are, we do not notify, we wait. Since changing the “batch mode” state will trigger a reducer to set the mode we will come back in this function to notify.

const appliedMiddleware = applyMiddleware(
  routesMiddleware,
  ...,
  ...,
  normalizerMiddleware);

const reducersTyped = {
  app: appReducer,
  ...,
  ...,
  router: routerReducer
};
const reducers = combineReducers(reducersTyped);

const store: Store<AppReduxState> = createStore(
  reducers,
  composeEnhancers(
    appliedMiddleware,
    batchedSubscribeEnhancer((notify: () => void, storeSnapshot: Store<AppReduxState>) => {
      if (!storeSnapshot.getState().app.isStoreInBatchMode) {
        notify();
      } 
    })
  ));

Here is an example of a normalizer based on the scenario discussed previously. Two different actions that are called at a different time of the software. Probably different API calls with a different response. When it receives the data, it calls an action. The middleware listens and act. In the example below, the “ACTION_A” receives 3 different entities that are handled by 3 different reducers. This would normally do 3 stores notification. But, since we using “batchNotification” function, who underneath wrap the 3 actions between 2 actions. One to set the “batch mode” to true and one to false. The resulting is the enhancer will only call one notification that will execute once the mapping and in consequence one render.

export const normalizerMiddleware: ExtendedMiddleware<AppReduxState> = <S>(api: MiddlewareAPI<S>) =>
    (next: Dispatch<S>) =>
        <A extends Actions<any>>(action: A): A => {
            if (typeof action.payload === "object") {
                if (action.type === ACTION_A) {
                    const normalizedResponse = normalize(action.payload, statusRoot);
                    console.log(normalizedResponse);
                    batchNotifications(
                        next,
                        actionOrgsNormalized(normalizedResponse.entities.org),
                        actionSitesNormalized(normalizedResponse.entities.site),
                        actionAppliancesNormalized(normalizedResponse.entities.cache),
                    );
                } else if (action.type === ACTION_B) {
                    const normalizedSiteForASingleOrg = normalize(action.payload, org);
                    next(actionSitesNormalized(normalizedSiteForASingleOrg.entities.site));
                }
            }
            return next(action);
        };

I won’t provide the “batchNotifications” code in here, but it’s literally a call to next(on) followed by a loop through the collection of action and next(off). You can do different pattern as well, nothing lock you to what I am demonstrating. Since you have access to the whole store, you could stop notification if the data is not done being normalized by looking at the data as well.

Redux Middleware: Calling next or dispatch?

Redux offers many ways to handle the flow of information in your system. One tool in the toolbox is using Middleware. I already discussed how we can leverage Middleware to do the heavy lifting instead of action creators. In this article, we will look at one question that you may stumble which is should I use next() or dispatch() withing my middleware?

Before digging into the main topic, let’s illustrate the flow on which we will analyze the question.

The illustration works from top to bottom. A component dispatches an action with the dispatch function from Redux library. The action contains a type (string) and a payload (data). Middlewares are injected in the flow with Redux at the configuration stage of Redux with the function applyMiddleware. For the hypothetic case illustrated, the configuration would be like the following code.

import { createStore, applyMiddleware } from "redux";
const appliedMiddleware = applyMiddleware(
  middleware1,
  middleware2,
  middleware3,
  middleware4,
  middleware5,
  middleware6);

const reducers = {
  reducer1,
  reducer2,
  reducer3,
  reducer4
};
const reducers = combineReducers(reducersTyped);

const store: Store<YourAppState> = createStore(reducers, composeEnhancers(appliedMiddleware));
class App extends React.Component<{}, YourAppState> {
  public render(): JSX.Element {
    return <Provider store={store}>

    </Provider>;
  }
}

The amount of middleware and reducer doesn’t need to coincide. They are orthogonal concepts. At some point, an action will be invoked via the dispatch function provided by Redux. Let’s call the action “A”. When the action is dispatched, Redux will pass the object to the first middleware. This one is responsible to do something or not. The middleware can inspect the type (string) and look if it knows what to do with it. Or, it can look at the payload and do something with it — it’s very flexible and unopinionated about the selection logic. The default behavior, when nothing is required, is to pass to the next middleware the action. This is done by calling the next function. As you can see in the image, middleware1 next connect to middleware2 and so on.

Imagine the scenario where you have an asynchronous call to an API in one of your middleware. This one should not block and must return something. Usually, you return the same action but before calling your API and wait for the response to come back (mostly wait the promise to be resolved). When the response comes back you have two choices: call next or dispatch a new action. The first option, calling next, will take the action you choose and pass it to the next middleware, bypassing all previous ones. Dispatching the action you choose will bring back the new action at the beginning of the stack to have this one move down the each middleware.

There is not an absolute solution in this regard. It’s a case by case solution. However, you mostly want to move the new action back to the front. In most cases, middleware might not do anything. For example, you may want to use next if your middleware is the last one and is doing the final manipulation to the data and doesn’t require any other middleware to alter the data before reaching the reducers. You might want to use next in cases where the new data may start new work from a previous middleware. This can be the case if when fetching data from a middleware require another middleware to fetch more data while analyzing the response.

Once the last middleware is reached and return for the last time next. The reducers are called in sequence and depending on their selection pattern may take the payload of the action and alter the store. In the case of the component dispatching data that require having a response from an API which is asynchronous, reducers will receive the initial action with the payload that requests the data, hence may do nothing to the store or just change a boolean to indicate that something is loading. Later, when the middleware dispatch or next the response, reducers will be called again and they may do something.

Finally, the loop is closed by having the store raising an event saying that the store has changed. From there Redux-React offers a “Provider” component that takes care to refresh the state or you can subscribe directly to the store to get notified a refresh the state manually. In both cases, the component is rendered and the changes are displayed to the user.

React and Redux without ActionCreator

Before digging into the main topic of not using action creator, let me establish some contexts. There is nothing white or black and this is even truer in regards to anything touching JavaScript these days. The official documentation of Redux talks about action creator but is very unopinionated about how the full flow should me. A few weeks ago, I was working in a Redux application at Netflix and find myself using the action creator approach, which is the natural way to me. However, my partner was not. Also, I found myself not using action creator in a particular flow as well, hence started to thinking about converging into a single approach which was to avoid having the action creator. I still believe action creator is a simple way to have a proper React and Flux flows of information, and in this article want to highlight a different way to work with Redux.

I like working with action creators and this is the first time I used Flux a few years ago. To me, it makes sense that a component initiate an action using the action creator. A parallel can be made if you are from Asp.Net MVC. The action creator is acting like the controller, receiving the action, and executing the logic before sending the information to be persisted. In Asp.Net MVC the controller would have delegated the logic into the service layer who would have manipulated the data with logic and pass along the transformed data to the persisted layer. If the service layer requires more data to execute any logic, it would call the persistent layer and continue its logic until the transformed data require to be saved. So far, nothing new for people who worked with Asp.Net MVC. The same approach can be followed with Redux. The component can dispatch to an action creator function. The action creator does its business logic by calling other classes and functions and if it needs more data can do an Ajax call, get the data and when ready dispatch an action to persist the information in the store which would be caught by the reducer and so on. So far, so good; so far, nothing novel here.

My partner was also doing something similar but was using a concept that is not present in Flux, neither in Asp.Net MVC, which is middleware. The middleware is a function that listens to every action and can decide to opt in or not. Redux loops through all the middleware right before the action read the reducers. This means that it’s pretty close to where the action creator is located. The main difference is that if we move the logic from the action creator to middleware naively we would end up having a lot of middleware. If you have 50 pages, with 50 action creators, this would result to 50 middlewares. It is also against the spirit of how to use middleware even if how to use middleware is not very documented or should I say opinionated. While you could in practice have a lot of middlewares, it becomes fast cumbersome. Middleware needs to be registered and that would end up having to register a lot of them which would also all be invoked on every action.

So what is the pros and cons of this middleware approach? Well, the pro is definitely that it remove some boilerplate. You have one level of indirection that is completely gone. The cons that come with the level of indirection is that you need a design that pushes later the business logic. We could have a 1-1 migration between action creators and middleware but that wouldn’t scale. It means that the middleware needs to be more generic. The guideline would be one middleware per source of data (API services for example) but you might see an issue there. If there is no logic being processed before reaching reducers it means that the store is having almost saw data. This is partially true. The data can be normalized in the middleware, but no business logic will be applied to the data. For example, if you are used having some sorting, filtering, and data manipulation to be stored as a result in the store you will need to change that pattern. The business logic is now moved in the function that does the mapping between the store and the property passed to the container component. This one will take the normalized data, do the denormalization and apply the logic. So far, no issue else than changing some habit about what is stored in the store.

The big difference is that you might be more confined in terms of how deep can be your logic. What I mean is that with the action creator, you could do additional calls to external services and doing additional calls. However, with the business logic at a later stage, this is impossible. It means that you need to anticipate which information might be required and do everything (if even possible) at the middleware level. This is a very important nuance between the action creators approach and the middleware.

The approach surrounding middleware allows great reusability of accessing external resources and remove the burden of adding an additional layer. It works great in scenarios that are more CRUD (creat-read-update-delete), less in scenarios that are more convoluted with deeper logic. I personally prefer the action creators pattern because of its universal application across potential scenarios at the cost of adding more boilerplate. However, it’s great to have a different pattern in hands.

NPM Useful Commands

This article will be pretty slim but can be helpful for more than just myself so I am sharing. Here are some commands available with NPM that you may not know that can be useful.

To know packages that are installed globally:

npm list -g --depth=0

To know where the packages are installed. It gives the global location if no node_modules folder in the direct folder parent tree:

npm root
npm root -g // The global folder

To know your NPM version and the actual released version

npm root

To know all available version of a library:

npm show react-native versions

To get all your direct dependencies current version and latest:

npm out --depth=0