TypeScript, React and Redux Part 4 : Multiple Returns from Action Creator

In this article, we will see how to execute more than a single action from a single call to an action creator. This will be useful for a scenario like requesting data where we expect the action creator to dispatch a loading state to have the user interface showing a loading animation and to invoke another dispatch when the data is received which stop the loading animation and load the information on the screen.

Previously, the action creator was returning an interface from the action. This means that the action creator was calling the action and this one was returning the type and values. The problem with this approach is that most of the time, an action is executed with a fast response and a second one was sent with the actual result. The first call allows to setup the user interface to display a spinner or any kind of loading experience, while the second one will stop this loading state to display the actual content.

This is where the middleware concept of Redux get in place. For the purpose of this article, we won’t go into detail about how middle-ware works, but will just use the open source middle-ware called “Thunk”.

npm install --save redux-thunk
npm install --save-dev @types/redux-thunk

This will allow us to return a Thunk Action instead of an object, which allows us to dispatch as many responses we want.

import { ThunkAction } from "redux-thunk";
import { Dispatch } from "redux";

export function applyFilter(): ThunkAction<void, IAppState, void> {
    return (dispatch: Dispatch<IUpdateFilterAction>, getState: () => IAppState, extra: any) => {
        setTimeout(() => {
            const fakePayload = {} as IResults; // Simulate date from response through Ajax response
            dispatch(actionApplyResponse(fakePayload));
        }, 1500);

        return dispatch(actionApplyRequest());
    };
}

In this example, we can see that we are referencing the ThunkAction class and Dispatch. The ThunkAction is the returned type which takes three type in its generic signature. The first one is the returned type we expect. In that case, I do not return anything, thus it is “void”. The second parameter is the type of the state in the store. This is useful because it allows us to interrogate the store inside the action creator. This is useful for validation purposed but also to computer possible value from existing values. The last type is any extra value to use. The example shows that the actionApplyRequest action is dispatched immediately and that the actionApplyReponse is dispatched 1.5 seconds later.

In this article, we brought a new dependency called Thunk that allows us to dispatch multiple actions instead of returning a single action. This allows us to handle an asynchronous scenario like fetching data from a remote source. This approach gave us the capability to consult the store as well which opens endless possibility in term of validations, data to use for data manipulation and so on.

Articles of the series:

  1. TypeScript, React and Redux
  2. TypeScript and Redux Store
  3. TypeScript Redux Store Binding
  4. TypeScript Redux Action Creators
  5. TypeScript, React and Redux Part 5 : Reducer with Different Actions

TypeScript, React and Redux Part 3 : Binding the Store and Component

In the previous article, we saw how to create a store in Redux and how to bind this one with the React-Redux library. We created a simple reducer, but an important piece was missing. In this article, we will define how to bind the store and the component. This will be useful to have Redux updating React components, but also to have the component to raise an event in the action creator.

We previously created the index.tsx which is the entry point of the web application. This one was creating the store, using the provider wrapper around the container component “app” and was hooking the component to an HTML tag. We never defined the container component “app”.

const store = createStore(appReducer);
ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
    , document.getElementById("main"));

A container component is different from a presentation component. This one is aware of Redux and its goal is to connect React and Redux. It must be a stateless component, which means that the container component doesn’t have any state — it’s just a function : the render function. In the following code, you can see the stateless function. It uses many presentation component. You can also see that it receives by parameter IAppProps which is the property. This will be injected by Redux with data from the store.

const App = (props: IAppProps) => (<div>
    <HeaderPanel
    />
    <div className="container">
        <div className="row">
            <Filters
                filters={props.model.filters}
                onApply={() => { console.log("to do soon"); }}
                filterChange={(filters: IFilters) => {
                    console.log("filter changed");
                    props.filterChange(filters);
                }}
            />
            <ResultPanel
                results={props.model.results}
            />
        </div>
    </div>
</div>
);

If we look at the interface signature, we can see that the IAppProps contains the IAppState which is exactly the type used by the reducer to initialize the store.

export interface IAppProps extends IAppDispatch {
    model: IAppState;
}

You can also notice that the interface extends IAppDispatch.

interface IAppDispatch {
    onApply: () => void;
    filterChange: (filters: IFilters) => void;
}

This interface contains all method callback passed down the presentation containers. It allows to have a good separation of concerns and have these presentation containers not aware of Redux’s action creator and reducer.

Now, at the heart of the goal of this article, how do we bind the state to the props used as parameter of this stateless container? We know the we should return inject an IAppProps and we know we have the store having a IAppState. What needs to be done is a mapping function that will transform one to the other.

const mapStateToProps = (state: IAppState) => {
    return {
        model: state,
    } as IAppProps
};

The second goal is how do we map the actions received by callback methods to the action creator. Very similar to the prop-state. We need a mapping function. The dispatch interface we defined as IAppDispatch is used to bind these actions to a concrete method in the actions creator.

const mapDispatchToProps = (dispatch: Dispatch<IAppState>): IAppDispatch => {
    return {
        onApply: () => {
            dispatch(updateFilter());
        },
        filterChange: (filters: IFilters) => {
            dispatch(filterChanged(filters));
        }
    } as IAppDispatch;
};

We finally needs to not return the simple stateless function, but to return the result of the Redux function connect.

export default connect(mapStateToProps, mapDispatchToProps)(App);

At that point, if the store is updated, the information will flow to the container component. If something happen, the action will be dispatched to the action creators and the reducer. In this article, we closed the loop by creating a simple React and Redux application that allow to have a simple action dispatched through an action creator to a reducer to modify the store to update our component. In the next article, we will see how to execute more than a single action from a single call to an action creator. This will be useful for scenario like requesting data where we expect the action creator to dispatch a loading state to have the user interface showing a loading animation and to invoke another dispatch when the data is received which stop the loading animation and load the information on the screen.

Articles of the series:

  1. TypeScript, React and Redux
  2. TypeScript and Redux Store
  3. TypeScript Redux Store Binding
  4. TypeScript Redux Action Creators
  5. TypeScript, React and Redux Part 5 : Reducer with Different Actions

JavaScript Fibonnaci Recursive, with Memoizer and Iterative

Fibonnaci numbers are a sequence of number that keep adding from previous result. It’s a common problem that can be resolve with few lines of code by using recursivity. The formula is F(x) = F(n-1) + F(n-1). The following code is a basic Fibonnaci implemented with a recursive loop.

function fib(x){
  if(x<=0){
    return 0;
  }
  if(x==1 || x ==2){
    return 1;
  } else{
  return fib(x-1) + fib(x-2);
  }
}

console.log("10:"+fib(10));

We can use a closure to keep in memory previous value. This increase the speed since you do not have to compute many time the same function. However, this solution will grow your memory consumption.

var fibMemoize = function(){
  var memoize = [0,1,1];
  var innerFib = function(x){
    var resultFromMemoize = memoize[x];
    if(resultFromMemoize === undefined){
      memoize[x] = innerFib(x-1) + innerFib(x-2);
      return memoize[x];
    } else {
      return resultFromMemoize;
    }
  };
  return innerFib;
}();

console.log("10:"+ fibMemoize(10));

It’s also possible to implement an iterative version of Fibonnaci. We do not need to keep an array since we won’t compute more than once every possibility (we do not have a branch of n-1 and n-2). In that case, what we do is always keeping the n-2 and n-1 result in a variable and keep swapping the value while iterating to the number desired.

function fibIterative(x){
  if(x<=0){
    return 0;
  }
  var n2 = 1;
  var n1 = 1;
  for(var i = 2; i < x-1; i++){
    var newValue = n2 + n1;
    n2 = n1;
    n1 = newValue;
  }
  return n2 + n1;
}

console.log("10 iterative:"+ fibIterative(10));

There is plenty of other solutions, but these three are the basic ones.

TypeScript, React and Redux Part 2 : Creating the Store and the Reducer

In the previous article, we discussed what is Redux and how the information flow through the data life cycle. This time, we will see more concretely how to bring Redux into a small React application written with TypeScript.

The first step is to get some NPM packages. We need TypeScript, React, React-Dom, Redux and React-Redux libraries.

npm install --save-dev typescript
npm install --save react
npm install --save react-dom
npm install --save redux
npm install --save react-redux
npm install --save-dev @types/react
npm install --save-dev @types/react-dom
npm install --save-dev @types/redux
npm install --save-dev @types/react-redux

In the example that we will explain, the life cycle starts from the file “index.tsx”.

In this basic example, we will use a single store with a single reducer. This means we can use the createStore function from Redux directly without using any combiners of any kind (this will be cover in a future article). This file contains almost more imports than code.

import * as React from "react";
import * as ReactDOM from "react-dom";
import { createStore } from "redux";
import App from "./components/containerComponents/App";
import { appReducer } from "./redux/reducers";
import { Provider } from "react-redux";

const store = createStore(appReducer);
ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
    , document.getElementById("main"));

The goal is to setup the store and the reducer. The store is where the data is stored and where the reducer will be invoked. To have the store being able to use a reducer, we need to pass down the reducer in the create store function. To have the store being able to notify our React’s components, we need to use a “react-redux” component. This component goal is to notify the React component to update. This helper is named “Provider” and come from “react-redux” and pass a store property which is the created store few lines above. The missing piece is the reducer to pass to the store. This is coming from your own file. In this example, it’s coming from a file that we will see in the next paragraph named “appReducer”.

The example allows the user to change some filter options to get picture depending on the selected criteria. The reducer will modify the state (store) depending on what the user selects from the form. The reducer will be called by the React component (see later in this article) with an action which the reducer will digest. That is why we import the action at the beginning of this file. The second important type of class to import is the contract/schema of the store. The reducer is the only one who modifies the state of the store, hence needs to know about the interface of the state. Finally, we need to import the action creator (we will see soon) which will indicate to the reducer which action that is active right now.

Below the imports, the file contains an initial state which is how the state should be if nothing has been yet initialized. This is the

import { FILTER_APPLIED, RESET, SHOW_RESULT, FILTER_CHANGED } from "./actions";
import { IAppState, IResults, IFilters } from "../models/filterModels";
import { IUpdateFilterActionCreator } from "./actionsCreator";

const initialState = {
    filters: {
        tags: [],
        isBlackAndWhite: false,
        startingDate: new Date(),
        endingDate: new Date(),
        numberOfPeople: 100,
        smileLevel: 0,
        happinessLevel: 0,
        peopleName: []
    } as IFilters
    , results: {
        pictureResults: []
    } as IResults
} as IAppState;

The final piece is the reducer code. The reducer is a single method that takes the state and the action. The state and the action come from the component. If you need to send a subset of the state there are multiple possibilities. You can use multiple states in the store and use a combined reduced (will be discussed in a future article) or copy the actual state (so immutable) and alter the modified value. The latter is what we will do.

export function appReducer(state: IAppState = initialState, action: IUpdateFilterActionCreator): IAppState {
    switch (action.type) {
        case RESET:
            return initialState;
        case FILTER_CHANGED:
            return Object.assign({}, state, {
                filters: action.filters
            }) as IAppState;
        case SHOW_RESULT:
            return Object.assign({}, state, {
                results: action.results
            }) as IAppState;
        default:
            return state
    }
}

The reducer looks for the action and alters the state by returning a new state. This is important to always return a new object with a brand new reference. This makes the store’s state immutable. If someone tries to change the value of the store somewhere else, it won’t affect the React components. In this example, we have 3 actions which one reset the filters to the initial state, one that changes the filter from the filters object received by the “Apply” button from the UI and one that will be executed once the filter got applied (after the request to the back-end returned a response.

In this article, we created a store with the createStore method provided by Redux. We wrapped our application component (App.tsx) in the entry component (Index.tsx) to allows the store to be a hook with react with the Provider component from “react-redux”. We saw how to create a reducer which is a function that takes the state and the action creator and return an immutable state which is why we call the reducer’s function a pure function. In the next article, we will explore the missing piece to hook actions from the component to the reducer we created.

Articles of the series:

  1. TypeScript, React and Redux
  2. TypeScript and Redux Store
  3. TypeScript Redux Store Binding
  4. TypeScript Redux Action Creators
  5. TypeScript, React and Redux Part 5 : Reducer with Different Actions

TypeScript, React and Redux Part 1 : The Big Picture

Redux is a state manager that allows flowing the data from component to the store and from the store to components. It is one of the most popular flux cycles at this moment. The reason for its popularity is mostly because of how everything is well separated and have its own unique goal. Once set up, it’s a chart to maintain and to extend. While Redux has a lot of documentations in term of videos, text tutorials and examples. However, Redux can be intimidating because of its steep learning curve. TypeScript is also not as well documented with Redux and require some more work to make it work. This is part 1 of many that will describe how to use TypeScript, React and Redux.

The first thing to understand is some of the terms used. The first one is “provider”. The provider is coming from the “react-redux” library. It’s a React’s component that wraps your main component.

For example, if your application main entry point is “App.tsx”, which use ReactDom. Render, then you need to import the “provider” component and wrap your “App” container.

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
    , document.getElementById("main"));

In term of code, almost nothing is changed. You have the same ReactDOM.render method, but the use of this new “provider” component. This component takes property named “store”. The store is the second term that is important. This one will keep the state of the application. State means it holds the JSON object that contains the whole data for your application. This means that the entry point component needs to create the store just before rendering the Provider & App component.

const store = createStore(appReducer);
ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
    , document.getElementById("main"));

This introduces us the third term which is “reducer”. To create a store you need to pass the application reducer. This one is a little bit more complex to understand. The store is not a store in the way of a SQL database, or a Local Storage or any kind of persistence. It’s a place where the JSON will live, but also where handle the transformation of the data. The transformation is where the logic resides. The return values of a reducer is always a copy, immutable of the actual state. It’s getting the actual state (JSON object) as a parameter and return back a JSON object with the same schema of the state that came in. For example, if the website allows having a different kind of filtering for the result, every user’s choice will be sent to a reducer that will change the state to set the value of the filter selected and the new state will be returned by the reducer which will be stored in the store. The store will automatically emit a change event which the “Provider” component will propagate.

In the world of Redux, there is a separation among components. There are two types. The first one is container component, the second one is presentation component. The second one is the easier to understand. It is a React’s component that doesn’t have any knowledge of Redux or any Flux pattern or life pattern. It receives properties to display and action is also part of delegate action passed by a property. The first type, the container component, is handling Redux. In our example, it’s App.tsx. It’s a stateless React component that is exported by using Redux’s “connect” function which has two parameters that take care of the mapping between Redux’s store state and the container component, and the other way around between the dispatcher actions to the component properties. The method that maps the state to the props allows to pass down a portion of the store instead of the whole store. The method that maps the dispatch to properties. This method will be invoked when the property of the action is invoked. This means that the return type must be part of the container component property type.

In this article, we saw some key concepts of Redux. We saw that the provider allows to glue Redux and React, and understand that components can be aware and not of Redux. The concept of reducer was introduced as a way to modify the state. Finally, we briefly exposed that we need to connect the container component with a specific method to bind React to Redux with the “mapDispatchToProps” and the method “mapStateToProps” to bind Redux to React. The second part will bring code to see how React and Redux can be used with the collaboration of TypeScript.

Articles of the series:

  1. TypeScript, React and Redux
  2. TypeScript and Redux Store
  3. TypeScript Redux Store Binding
  4. TypeScript Redux Action Creators
  5. TypeScript, React and Redux Part 5 : Reducer with Different Actions