-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnested-state.js
56 lines (49 loc) · 1.4 KB
/
nested-state.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
const redux = require('redux');
const createStore = redux.createStore;
const produce = require('immer').produce;
//Step1 : make initial State
const initialState = {
name: 'Karthik',
address: {
street: '1234 main road',
city: 'bentonville',
state: 'AR'
},
};
//Step2: create constant action type
const CITY_UPDATED = 'CITY_UPDATED';
//Step3: define action creator to update the state
const updateCity = (city) => {
return {
type: CITY_UPDATED,
payload: city
}
}
//Step4: create reducer
const reducer = (state = initialState, action) => {
switch (action.type) {
case CITY_UPDATED:
// return {
// ...state,
// address: {
// ...state.address,
// city: action.payload
// }
// }
//its hard to keep track of nested state and here's why immer.produce comes to our aid
return produce(state, (draft) => {
draft.address.city = action.payload;
})
default: {
return state;
}
}
}
//Step 5: Create store, dispatch actions
const store = createStore(reducer);
console.log('Initial state: ', store, store.getState());
const unsubscribe = store.subscribe(() => {
console.log('Updated State: ', store.getState());
})
store.dispatch(updateCity('benton county'));
unsubscribe();