javascript - React Flux - dispatching within a dispatch - how to avoid? -
i seem have encountered situation cannot avoid dispatch-within-a-dispatch problem in flux.
i've read few similar questions regarding problem none of them seem have solution besides settimeout
hacks, avoid.
i'm using alt.js instead of flux think concepts same.
scenario
imagine component renders login form. when user logs in, triggers xhr responds authentication information (eg. user name), , fetches secure data based on authentication information , renders instead of login form.
the problem have when attempt fire action fetch data based on xhr response, still in dispatch of login_response
action, , triggers dreaded
error: invariant violation: dispatch.dispatch(...): cannot dispatch in middle of dispatch.
example
i have created this jsfiddle demonstrate problem.
i have wrapper
component either renders login button or contents
child component, based on whether user set in mystore
.
- first, login button rendered in
wrapper
component. - clicking button dispatches
login
action. - after delay,
login_response
action dispatched (via async mechanism in alt.js). - this action triggers
mystore
update user name. wrapper
component observes store change , updates state.- this causes
wrapper
rendercontent
component instead of login button. content
component, on mount, attempts dispatchfetch_data
action, fails because dispatcher still dispatchinglogin_response
. (if wrapfetch_data
dispatch insettimeout
works, feels hack).
variations of seems common scenario. in fact related questions have similar scenario, no or concrete answers.
- react - authentication process : cannot dispatch in middle of dispatch
- dispatching cascading/dependent async requests in flux/react
- flux dispatch.dispatch(...): cannot dispatch in middle of dispatch
is there intrinsically wrong data flow? proper flux way of doing this?
this common problem dispatching in componentdidmount
in many libraries. solution wrap dispatches in react's batched updates; luckily, alt allows batchingfunction
option:
var alt = new alt({ // react.addons.batchedupdates deprecated: // batchingfunction: react.addons.batchedupdates // use instead in newer versions of react // see https://discuss.reactjs.org/t/any-plan-for-reactdom-unstable-batchedupdates/1978 batchingfunction: reactdom.unstable_batchedupdates });
see https://jsfiddle.net/binarymuse/qftyfjgy/ working example , this fluxxor issue description of same problem in different framework.
Comments
Post a Comment