Last active
August 22, 2017 20:01
-
-
Save craigtaub/365d82c198b669572ae5d7785441d348 to your computer and use it in GitHub Desktop.
Vanilla Redux
This file contains hidden or 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
// -------- declaration of Store, reducers, actions -------- -------- | |
function createStore(reducers) { | |
let currentSubscribers = []; | |
const dispatch = (action) => { | |
const currentState = reducers[action.type](currentState, action); | |
for (let i = 0; i < currentSubscribers.length; i++) { | |
currentSubscribers[i](currentState); | |
} | |
} | |
const subscribe = (subscriber) => { | |
currentSubscribers = [...currentSubscribers, subscriber]; | |
} | |
return { | |
dispatch, subscribe | |
} | |
} | |
const defaultState = {}; | |
const reducers = { | |
['FIRST_ACTION']: (state = defaultState, action) => { | |
const newState = Object.assign({}, state, action); | |
return newState.payload; | |
} | |
} | |
const myFirstAction = (data) => ({ | |
type: 'FIRST_ACTION', | |
payload: data | |
}); | |
// -------- create component -------- -------- -------- -------- | |
const MyComponent = (props) => { | |
console.log('prop:', props) | |
} | |
// -------- create store, subscribe + dispatch -------- -------- -------- | |
const store = createStore(reducers); | |
store.subscribe(MyComponent) | |
store.dispatch(myFirstAction('some-data')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment