-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredux-basic.js
42 lines (34 loc) · 936 Bytes
/
redux-basic.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
const redux = require("redux");
const initialState = {
counter: 0
};
//make store
const createStore = redux.createStore;
//make Reducer
const rootReducer = (state = initialState, action) => {
if (action.type == "INC_COUNTER") {
return {
...state,
counter: state.counter + 1
};
}
if (action.type == "ADD_COUNTER") {
return {
...state,
counter: state.counter + action.payload
};
}
return state;
};
const store = createStore(rootReducer);
//ADDING SUBSCRIPTION TO REDUX - TO INFORM ALL STATE CHANGE
//SUBSCRIBE MUST COME BEFORE ACTIONS
store.subscribe(() => {
//FUNCTION WILL BE CALLED WHEN STATE IS CHANGED @@@@
console.log("[REDUX UPDATED]===////=== ", store.getState());
});
console.log(store.getState()); //output {counter: 0}
//DISPATCHING ACTIONS
store.dispatch({ type: "INC_COUNTER" });
store.dispatch({ type: "ADD_COUNTER", payload: 20 });
console.log(store.getState()); //output {counter: 21}