-
-
Save shtakai/cf19a7a27c1663f4914c87c881d40a67 to your computer and use it in GitHub Desktop.
Redux in 30 lines
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) { | |
const store = { | |
state: {}, | |
reducer, | |
dispatch(action) { | |
this.state = this.reducer(action, this.state) | |
} | |
} | |
store.dispatch({}) | |
return store | |
} | |
function combineReducers(reducers) { | |
return (action, state) => { | |
const nextState = {} | |
for (const key of Object.keys(reducers)) { | |
nextState[key] = reducers[key](action, state[key]) | |
} | |
return nextState | |
} | |
} | |
module.exports = { | |
createStore, | |
combineReducers | |
} |
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
const { createStore, combineReducers } = require('./redux.js') | |
function countReducer(action, count = 0) { | |
switch(action.type) { | |
case 'INC': | |
count += 1 | |
break; | |
default: | |
break; | |
} | |
return count | |
} | |
function helloReducer(action, greeting = 'Hello, John!') { | |
switch(action.type) { | |
case 'NAME': | |
greeting = `Hello, ${action.payload}!` | |
break; | |
default: | |
break; | |
} | |
return greeting | |
} | |
const reducer = combineReducers({ count: countReducer, hello: helloReducer }) | |
const store = createStore(reducer) | |
console.log(store.state) | |
store.dispatch({ type: 'INC' }) | |
console.log(store.state) | |
store.dispatch({ type: 'INC' }) | |
console.log(store.state) | |
store.dispatch({ type: 'NAME', payload: 'Sam' }) | |
console.log(store.state) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment