main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// There area lot more checks in the Redux lib but this gets the point across.
function createStore(reducer, initialState) {
  let currentState = initialState;
  const listeners = [];

  function getState() {
    return currentState;
  }

  function subscribe(listener) {

    if (typeof listener !== 'function') {
      throw new Error('A listener must be a function');
    }

    listeners.push(listener);
    
    return function unsubscribe() {
      const index = listeners.indexOf(listener);
      listeners.splice(index, 1);
    }
  }

  function dispatch(action) {
    currentState = reducer(currentState, action);
    
    listeners.forEach(listener => listener());
    
    return action;
  }

  dispatch({ type: 'INIT'});

  return {
    getState,
    subscribe,
    dispatch,
  };
}
// End the Redux implementation


// Reducer
function reducer(state = { firstName: 'John', lastName: 'Smith' }, action) {
  switch (action.type) {
    case 'UPDATE_FIRSTNAME':
      return {
          ...state,
          firstName: action.payload,
        };
    case 'UPDATE_LASTNAME':
      return {
        ...state,
        lastName: action.payload,
      };
    default:
      return state;
  }
}

// Action creators
const updateFirstName = firstName => ({
  type: 'UPDATE_FIRSTNAME',
  payload: firstName,
});

const updateLastName = lastName => ({
  type: 'UPDATE_LASTNAME',
  payload: lastName,
});

// Create the store
const store = createStore(reducer);

// Get initial state
console.log(`INITIAL STATE: ${JSON.stringify(store.getState())}`);

// Subscribe to state changes
const unsub = store.subscribe(() => {
  console.log(`Subscription fired`, JSON.stringify(store.getState()));
})

// Dispatch an action
store.dispatch(updateFirstName('Tommy'));

// Unsubscribe our listener
unsub();

// Dispatch another action
store.dispatch(updateLastName('Watson'));

// Get the current state
console.log(JSON.stringify(store.getState()));
Babel Compiler v6.4.4 Copyright (c) 2014-2015 Sebastian McKenzie