Redux simple implementation
This file contains 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; | |
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