This is a topic that has been covered before, but I am still haven't quite found an answer I like and would love some advice.
I am having the following issue. My app contains an action called CREATE_RESPONSE, which creates a new response record and pushes it into the responses state. The action creator for this action is dispatched from my component when a user clicks a button.
onClick={() => { this.props.createResponse(); }} Now, after the user does this, I would like to open a modal for this new response. This modal relies on the new response state change, so must happen after createResponse.
The most intuitive solution for me would be to use a callback, but I believe this represents a Redux anti-pattern.
The other way would be to listen to response state changes, and then dispatch an action whenever the number of responses has changed (something similar to the subscribe example: http://redux.js.org/docs/api/Store.html#subscribe)
function responses(state) { return state.responses.size } let currentValue function handleChange() { let previousValue = currentValue currentValue = responses(store.getState()) if (previousValue !== currentValue) { // Dispatch action here } } store.subscribe(handleChange) The issue here is we are responding to all state changes that fulfill this condition. In my app, this incorrectly gets triggered on page load.
So my question boils down to: what is the best way to dispatch an action in response to a state change?
EDIT
Here are simplified versions of my Modal and Response reducers, respectively:
Modal
const modalState = Immutable.Map({ isOpen: false, view: null, modalProps: {} }); export const modal = (state = modalState, action) => { switch (action.type) { ... } } Responses
const responseRecord = Immutable.Record({ id: null, ... }); export const responses = (state = Immutable.List([]), action) => { switch (action.type) { case 'CREATE_RESPONSE': newResponse = new responseRecord(...); state = state.unshift(newResponse); return state; ...
createResponse?