Search code examples
reactjsflux

Is accessing state in an action a violation of Flux principles?


I am new to React and am writing an infinite scroll functionality.

window.addEventListener( 'scroll', DutyActions.scrollDuties );

On each scroll event, I call the action scrollDuties, which fetches data from the server. Then a server action called loadDuties is called to pass the response to the store, which it broadcasts to the views.

The issue is that on a fast scroll it makes multiple hits to API because the second scroll event fires before the setState({loading: true}) statement renders on the page. I think the only solution is to read the state in the action and make the ajax hit only if a loading flag is false.

Would this violate Flux principles?


Solution

  • The Redux flavor of Flux handles this situation in the action elegantly by way of the redux-thunk middleware. In that paradigm the action creator can return a function which has a parameter to get the store. Its dispatcher knows how to evaluate this function so that the store can be exposed to the action, without creating an explicit store dependency in the action.

    With more standard Flux implementations, to achieve the same decoupling, I believe you would have to pass a store parameter to the action from the component. Maybe something along the lines of:

    doScrollAction: function (scrollParam) {
      var isLoadingStore = IsLoadingStore.getAll()
      DutyActions.scrollDuties(scrollParam, IsLoadingStore)
    }
    
    window.addEventListener( 'scroll', doScrollAction );