Skip to content

Instantly share code, notes, and snippets.

@gaearon
Created June 16, 2015 12:06
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaearon/1cb2db924b7593f5a515 to your computer and use it in GitHub Desktop.
Save gaearon/1cb2db924b7593f5a515 to your computer and use it in GitHub Desktop.
Basic action monitoring for Redux
// 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>
);
}
};
}
@silentroach
Copy link

you can make a gist with multiple files

@muhanad40
Copy link

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