-
Notifications
You must be signed in to change notification settings - Fork 0
/
advanceRedux.js
71 lines (58 loc) · 1.41 KB
/
advanceRedux.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
// Collect dom elements.
const incrementEl = document.getElementById("increment");
const decrementEl = document.getElementById("decrement");
const counterEl = document.getElementById("counter");
// Initial State;
const initialState = {
value: 0,
};
// Action indentifiers;
const INCREMENT = "increment";
const DECREMENT = "decrement";
// Action creator.
const increment = (value) => {
return {
type: INCREMENT,
payload: value
}
};
const decrement = (value) => {
return {
type: DECREMENT,
payload: value
}
};
// Create reducer function.
const counterReducer = (state = initialState, action) => {
if(action.type === INCREMENT){
return {
...state,
value: state.value + action.payload,
};
} else if(action.type === DECREMENT){
return {
...state,
value: state.value - action.payload,
};
} else {
return state;
}
};
// create store.
const store = Redux.createStore(counterReducer);
// Create render function.
const render = () => {
const state = store.getState();
counterEl.innerText = state.value.toString();
};
// Initially state.
render();
// Send to subscriber.
store.subscribe(render);
// Button action.
incrementEl.addEventListener("click", () => {
store.dispatch(increment(5))
});
decrementEl.addEventListener("click", () => {
store.dispatch(decrement(5))
});