Last active
March 4, 2019 11:55
-
-
Save microcipcip/25d63741c4a7ebf138aae2f61e4cc566 to your computer and use it in GitHub Desktop.
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