Created
October 29, 2016 14:14
-
-
Save inooid/33af8ae5bb75c253faa4c547e0cbf89b to your computer and use it in GitHub Desktop.
An attempt to teach people Redux on stream
This file contains hidden or 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 createStore = require('redux').createStore; | |
// constants | |
const CHANGE_NAME = 'CHANGE_NAME'; | |
const CHANGE_AGE = 'CHANGE_AGE'; | |
const CHANGE_NAME_AND_JOB = 'CHANGE_NAME_AND_JOB'; | |
// actions | |
function changeName(name) { | |
return { | |
name: name, | |
type: CHANGE_NAME, | |
}; | |
} | |
function changeAge(number) { | |
return { | |
age: number, | |
type: CHANGE_AGE | |
}; | |
} | |
function changeNameAndJob(name, job) { | |
return { | |
name: name, | |
job: job, | |
type: CHANGE_NAME_AND_JOB, | |
} | |
} | |
// Reducers | |
function nameReducer(state = '', action) { | |
switch (action.type) { | |
case CHANGE_NAME: | |
case CHANGE_NAME_AND_JOB: | |
return action.name; | |
default: | |
return state; | |
} | |
} | |
function ageReducer(state = null, action) { | |
if (action.type === CHANGE_AGE) return action.age; | |
return state; | |
} | |
const currentJobInitialState = { | |
id: null, | |
name: null, | |
address: null, | |
}; | |
function currentJobReducer(state = currentJobInitialState, action) { | |
switch (action.type) { | |
case CHANGE_NAME_AND_JOB: | |
return Object.assign({}, state, action.job); | |
default: | |
return state; | |
} | |
} | |
function rootReducer(state = {}, action) { | |
return { | |
name: nameReducer(state.name, action), | |
age: ageReducer(state.age, action), | |
currentJob: currentJobReducer(state.currentJob, action), | |
}; | |
} | |
const storeInstance = createStore(rootReducer); | |
const arrayOfStates = []; | |
storeInstance.subscribe(() => { | |
arrayOfStates.push(storeInstance.getState()); | |
console.log('current state:', storeInstance.getState()); | |
}); | |
storeInstance.dispatch(changeName('Boyd')); | |
storeInstance.dispatch(changeName('Bob')); | |
storeInstance.dispatch(changeName('uoclv')); | |
storeInstance.dispatch(changeAge(200)); | |
storeInstance.dispatch(changeName('Bob')); | |
storeInstance.dispatch(changeNameAndJob('Boyd', { id: 1, name: 'Boyd Inc.', address: 'ABC Street 1997' })); | |
arrayOfStates.forEach((state, index) => { | |
console.log(`State #${index + 1}:`, state); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment