1import { createStore } from 'redux'
2
3/**
4 * This is a reducer, a pure function with (state, action) => state signature.
5 * It describes how an action transforms the state into the next state.
6 *
7 * The shape of the state is up to you: it can be a primitive, an array, an object,
8 * or even an Immutable.js data structure. The only important part is that you should
9 * not mutate the state object, but return a new object if the state changes.
10 *
11 * In this example, we use a `switch` statement and strings, but you can use a helper that
12 * follows a different convention (such as function maps) if it makes sense for your
13 * project.
14 */
15function counter(state = 0, action) {
16 switch (action.type) {
17 case 'INCREMENT':
18 return state + 1
19 case 'DECREMENT':
20 return state - 1
21 default:
22 return state
23 }
24}
25
26// Create a Redux store holding the state of your app.
27// Its API is { subscribe, dispatch, getState }.
28let store = createStore(counter)
29
30// You can use subscribe() to update the UI in response to state changes.
31// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
32// However it can also be handy to persist the current state in the localStorage.
33
34store.subscribe(() => console.log(store.getState()))
35
36// The only way to mutate the internal state is to dispatch an action.
37// The actions can be serialized, logged or stored and later replayed.
38store.dispatch({ type: 'INCREMENT' })
39// 1
40store.dispatch({ type: 'INCREMENT' })
41// 2
42store.dispatch({ type: 'DECREMENT' })
43// 1