Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jslnriot
Last active August 12, 2017 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jslnriot/c2f317f30b888221b536a9ec2f0aa108 to your computer and use it in GitHub Desktop.
Save jslnriot/c2f317f30b888221b536a9ec2f0aa108 to your computer and use it in GitHub Desktop.
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