Skip to content

Instantly share code, notes, and snippets.

@microcipcip
Last active March 4, 2019 11:55
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Redux simple implementation
function createStore(reducer, initialState) {
let state = initialState;
const listeners = [];
const subscribe = listener => listeners.push(listener);
const getState = () => state;
const dispatch = action => {
state = reducer(state, action);
listeners.forEach(l => l());
};
return {
subscribe,
getState,
dispatch
};
}
const messagesReducer = (state, action) => {
switch (action.type) {
case "ADD_MESSAGE":
return { ...state, messages: state.messages.concat(action.message) };
default:
return state;
}
};
const messagesInitState = { messages: [] };
const addMessageAction = message => ({ type: "ADD_MESSAGE", message });
const store = createStore(messagesReducer, messagesInitState);
const listener = () => {
console.log("Current state: ");
console.log(store.getState());
};
store.subscribe(listener);
store.dispatch(addMessageAction("Hello Mark!"));
store.dispatch("Wrong action, without 'type' property, nothing happens!");
store.dispatch(addMessageAction("Hello Mark again!"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment