Skip to content

Instantly share code, notes, and snippets.

@LondonAppDev
Forked from microcipcip/redux.js
Created March 4, 2019 11:55
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 LondonAppDev/5a0420a3c1bdac6913f4b487badf15d9 to your computer and use it in GitHub Desktop.
Save LondonAppDev/5a0420a3c1bdac6913f4b487badf15d9 to your computer and use it in GitHub Desktop.
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