Last active
March 15, 2017 12:35
-
-
Save thevangelist/472b8e0ed020ea2c593e2e38e388eed4 to your computer and use it in GitHub Desktop.
Redux stores initialization, dispatchers and reducer in a nutshell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const userReducer = (state={}, action) => { | |
switch(action.type) { | |
case 'CHANGE_NAME': { | |
// Immutable way | |
state = {...state, name: action.payload} | |
break; | |
} | |
case "CHANGE_AGE": { | |
state = {...state, age: action.payload} | |
break; | |
} | |
} | |
return state; | |
}; | |
const defaults = {} | |
const tweetsReducer = (state=[], action) => { | |
return state; | |
}; | |
// Limit changing of user to userReducer | |
const reducers = combineReducers({ | |
user: userReducer, | |
tweets: tweetsReducer | |
}) | |
const store = createStore(reducers); | |
store.subscribe(() => { | |
console.log('Store changed', store.getState()) | |
}) | |
// type is mandatory, payload's name can be changed | |
// one action can trigger multiple side effects, that are completely de-coupled from each another | |
store.dispatch({ type: 'CHANGE_NAME', payload: 'Will' }); | |
store.dispatch({ type: 'CHANGE_AGE', payload: 29 }); | |
store.dispatch({ type: 'CHANGE_AGE', payload: 23 }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment