Last active
August 12, 2017 03:43
-
-
Save jslnriot/c2f317f30b888221b536a9ec2f0aa108 to your computer and use it in GitHub Desktop.
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
function createStore(reducer, initialState) { | |
let state = initialState; | |
// Setup listners to keep track of when the state is changed | |
// to triger rerenders (observer pattern) | |
const listeners = []; | |
const subscribe = (listener) => ( | |
listeners.push(listener) | |
); | |
const getState = () => (state); | |
const dispatch = (action) => { | |
state = reducer(state, action); | |
// call each listener function when the state is changed | |
// its just a notification that state is changed | |
listeners.forEach(l => l()); | |
}; | |
return { | |
subscribe, | |
getState, | |
dispatch, | |
}; | |
} | |
function reducer(state, action) { | |
if(action.type === 'ADD_MESSAGE') { | |
return { | |
messages: state.messages.concat(action.message), | |
} | |
}; | |
if(action.type === 'DELETE_MESSAGE') { | |
return { | |
messages: [ | |
...state.messages.slice(0, action.index), | |
...state.messages.slice( | |
action.index + 1, state.messages.length | |
), | |
], | |
}; | |
}; | |
return state; | |
} | |
// set initial state to pass into to store | |
const initialState = { messages: [] }; | |
// initialize the store | |
const store = createStore(reducer, initialState); | |
class Messages extends React.Component { | |
componentDidMount() { | |
store.subscribe(() => this.forceUpdate()); | |
} | |
render() { | |
const messages = store.getState().messages; | |
return ( | |
<div className='ui segment'> | |
<MessageView messages={messages} /> | |
<MessageInput /> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment