Last active
August 4, 2016 11:00
-
-
Save sancau/1e13f953733cd4b43f0c798cfe2e8fac to your computer and use it in GitHub Desktop.
Basic redux actions handling with multiple reducers
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
import { applyMiddleware, combineReducers, createStore } from 'redux'; | |
////////////////////////////////////////////////////// | |
const userReducer = (state={}, action) => { | |
switch (action.type) { | |
case 'CHANGE_NAME': { | |
return {...state, name: action.payload} | |
} | |
case 'CHANGE_AGE': { | |
return {...state, age: action.payload} | |
} | |
case 'ADD_TWEET': { | |
return {...state, tweets: !state.tweets ? 1 : state.tweets + 1 } | |
} | |
default: return state; | |
} | |
}; | |
////////////////////////////////////////////////////// | |
const tweetsReducer = (state=[], action) => { | |
switch (action.type) { | |
case 'ADD_TWEET': { | |
return state.concat([action.payload]); | |
} | |
case 'ERROR': { | |
throw Error('Error occured..'); | |
} | |
default: return state; | |
} | |
}; | |
////////////////////////////////////////////////////// | |
// basic middleware | |
const logger = (store) => (next) => (action) => { | |
console.log('action fired', action); | |
next(action); | |
}; | |
const error = (store) => (next) => (action) => { | |
try { | |
next(action); | |
} catch(e) { | |
console.error('Error came in..'); | |
} | |
}; | |
////////////////////////////////////////////////////// | |
const reducers = combineReducers({ | |
user: userReducer, | |
tweets: tweetsReducer | |
}); | |
////////////////////////////////////////////////////// | |
const middleware = applyMiddleware(logger, error); | |
const store = createStore(reducers, middleware); | |
store.subscribe(() => { | |
console.log(store.getState()); | |
}); | |
////////////////////////////////////////////////////// | |
console.log(store.getState()); | |
store.dispatch({type: 'CHANGE_NAME', payload: 'Sancau'}); | |
store.dispatch({type: 'CHANGE_AGE', payload: 29}); | |
store.dispatch({type: 'ADD_TWEET', payload: {title: 'ASDASD'} }); | |
store.dispatch({type: 'ERROR', payload: {title: 'ASDASD'} }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment