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.

  1. first, login button rendered in wrapper component.
  2. clicking button dispatches login action.
  3. after delay, login_response action dispatched (via async mechanism in alt.js).
  4. this action triggers mystore update user name.
  5. wrapper component observes store change , updates state.
  6. this causes wrapper render content component instead of login button.
  7. content component, on mount, attempts dispatch fetch_data action, fails because dispatcher still dispatching login_response. (if wrap fetch_data dispatch in settimeout works, feels hack).

variations of seems common scenario. in fact related questions have similar scenario, no or concrete answers.

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

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -