Created
June 16, 2015 12:06
-
-
Save gaearon/1cb2db924b7593f5a515 to your computer and use it in GitHub Desktop.
Basic action monitoring for 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
// App.js | |
import { Provider, Connector } from 'redux/react'; | |
import monitor from './monitor/index'; | |
const store = composeStores(stores); | |
const { dispatcher, ActionLog } = monitor(createDispatcher(store)); | |
const redux = createRedux(dispatcher); | |
export default class App { | |
render() { | |
return ( | |
<div> | |
<Provider redux={redux}> | |
{::this.renderRoot} | |
</Provider> | |
<ActionLog /> | |
</div> | |
); | |
} | |
renderRoot() { | |
// ... | |
} | |
} | |
// monitor/index.js | |
import createActionLog from './createActionLog'; | |
export default function monitor(dispatcher) { | |
const actionListeners = []; | |
function recordAction(action) { | |
actionListeners.forEach(listener => listener(action)); | |
} | |
function monitoringDispatcher(initialState, setState) { | |
let dispatch = dispatcher(initialState, setState); | |
function monitoringDispatch(action) { | |
recordAction(action); | |
return dispatch(action); | |
} | |
return monitoringDispatch; | |
} | |
function listenToActions(listener) { | |
actionListeners.push(listener); | |
return () => { | |
actionListeners.splice(actionListeners.indexOf(listener), 1); | |
}; | |
} | |
return { | |
dispatcher: monitoringDispatcher, | |
ActionLog: createActionLog(listenToActions) | |
}; | |
} | |
// monitor/createActionLog.js | |
import React, { Component } from 'react'; | |
export default function createActionLog(listenToActions) { | |
return class ActionLog extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { actions: [] }; | |
} | |
componentWillMount() { | |
this.stopListening = listenToActions(::this.handleAction); | |
} | |
handleAction(action) { | |
this.setState(({ actions }) => ({ | |
actions: [...actions, action] | |
})); | |
} | |
componentWillUnmount() { | |
this.stopListening(); | |
} | |
handleClear() { | |
this.setState({ | |
actions: [] | |
}); | |
} | |
render() { | |
return ( | |
<div> | |
<a href='#' onClick={::this.handleClear}> | |
Clear | |
</a> | |
{this.state.actions.map((action, index) => | |
<p key={index}>{JSON.stringify(action)}</p> | |
)} | |
</div> | |
); | |
} | |
}; | |
} |
I haven't tried this, but if this monitors actions and logs them, could this feature be added to redux. I'm trying to write a test where a component is expected to dispatch an action when an element inside it has been clicked. I don't know how else to do this.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you can make a gist with multiple files