State machine in JavaScript – How to build your own Redux like engine

This article will describe shortly how to build Redux-like state machine engine. So shortly what we need to define state machine?
– State itself (method which will deliver the state)
– Subscribe method (which will subscribe to state changes)
– Dispatch method (which will execute changes of our state engine)

Redux like engine – Step 1 – Draft of state management function

Lets define the draft of Redux-like function with previously defined methods getState, dispatch and subscribe. Parameter of our state managing function will be reducer – function which will describe how state should behave on given action.

const createStore = (reducer) => {
        let state;

        const getState = () => state;

        const dispatch = () => console.log('this method will execute change of state');

        const subscribe = () => console.log('this method will subscribe to changes on state);

        return {
            getState,
            dispatch,
            subscribe
        }
    };

Defined arrow function will return three methods:
1. getState – which will return our current state
2. dispatch – dispatcher of actions
3. subscribe – method which subscribes to state changes

Inside createStore function we defined state. This is the variable which keeps our current state. If we want to have a direct access to state we need to invoke getState method.

Redux like engine – Step 2 – Initial State

Our Redux-like engine won’t work without reducer and initial state. In this section let’s define initial state. Let’s imagine that we are developing game and one action of the game will be related to shots made by user. So when user will be clicking on screen or touching screen on mobile devices this action will be invoked. After invoking this action our state will be changed. In this case the number of shots made by user will be incremented. Initially it will be equal 0.

const initialState = {
    shots: 0
};

Redux like engine – Step 3 – Reducer

In this section we will define our reducer which will describe how our state should be changed after dispatching / executing given action. Reducer will get two params:
1. Initial state (defined previously)
2. Action

Action is an object with two parameters:
1. type
2. payload

Initially we will describe how our state should behave when user will invoke SHOT action.

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'SHOT':
           state = {
                ...state,
                shots: state.shots +1
            }
            return state;
        default:
            return state;
    }
}

To make interpretation of our reducer function lets imagine that we want to invoke action SHOT. To do it we have to pass to reducer action object like

{
    type: 'SHOT'
}

Redux like engine – Step 4 – Body of state management function

Let’s make our state usable. To do it we need to define two methods inside it
1. subscribe
2. dispatch

Before subscribe function will be created we have to define listeners inside createStore. Listeners will be an array of elements which will subscribe to our state and will react on each change of the state.

const createStore = (rootReducer) => {
    let state;
    let listeners = [];

    const getState = () => state;

    const dispatch = action => {
        state = rootReducer(state, action);
        listeners.forEach(listener => listener(state));
    };

    const subscribe = (listener) => {
        listeners.push(listener);

        return () => {
            listeners = listeners.filter(l => l !== listener)
        }
    };

    return {
        getState,
        dispatch,
        subscribe
    }
};

Redux like engine – Step 5 – Combine and run

Lets make a short tests. In this subchapter we will combine reducer and our statemanagement engine. At the end of code we will make an instance of store, we will subscribe to it and will get its value.

const initialState = {
    shots: 0
};

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'SHOT':
          console.log('shot')
           state = {
                ...state,
                shots: state.shots +1
            }
            return state;
        default:
            return state;
    }
};

const createStore = (rootReducer) => {
    let state;
    let listeners = [];

    const getState = () => state;

    const dispatch = action => {
        state = rootReducer(state, action);
        listeners.forEach(listener => listener(state));
    };

    const subscribe = (listener) => {
        listeners.push(listener);

        return () => {
            listeners = listeners.filter(l => l !== listener)
        }
    };

    return {
        getState,
        dispatch,
        subscribe
    }
};

const storeInstance = createStore(reducer);

console.log(storeInstance.getState());

storeInstance.subscribe(() => console.log('subscriber shots:', + storeInstance.getState().shots))

storeInstance.dispatch({type: 'SHOT'});
storeInstance.dispatch({type: 'SHOT'});
storeInstance.dispatch({type: 'SHOT'});

console.log(storeInstance.getState());

After running this code we will see console log similar to this one:

"shot"
"subscriber shots:" 1
"shot"
"subscriber shots:" 2
"shot"
"subscriber shots:" 3
[object Object] {
  shots: 3
}

Everytime “dispatch” function is ran it gives us information about sum of shots. Additionally we can see that reducer function is ran (“shot” log).

State management – Isn’t it easy? 😀

Please follow and like us:
error

Published by Piotr Sikora

Piotr Sikora is Front End Team Manager @ Sourceful. MeetJS Kielce Committee member. JavaScript enthusiast. With passion to MTB (http://ckbikers.com)

Leave a comment

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