Search code examples
javascriptreactjsflux

React + Flux - Unload page on multi-page


Consider a multi-page application where, when you open a page, it starts a timer responsible for fethcing data every n seconds. Now consider you want to go to another page, how would you guarantee that the timer will be stopped (as it won't be needed on the second page).

I would implement it as the following:

App.jsx

onClickNavigateToPageA: function() { AppActions.goToA(); }

AppActions.js

goToA: function() {
   DispatchActionToLoadComponentPageA();
   DispatchActionToStartTimer();
}

Now I click to go to page B. How to tell the timer to stop? If I do this (through an action, I believe) on componentWillUnmount I would be dispatching an action during an action (the action to load page B), so it is wrong.

The right way would be to register a callback (that would call an action to disable the timer) right after loading page A and then calling it when loading any other page? To my knowledge, the store should never now about the api used to fetch data from the server (including the timer, it should be on action creators).


Solution

  • You can dispatch actions with any JSON payload you want, which means you can group action types by properties of the dispatched action itself. In this case the payload from DispatchActionToLoadComponentPageA might be:

    { 
        type: 'pageLoad',
        page: 'pageA'
    }
    

    Which would be different from other types of actions you might dispatch like:

    { 
        type: 'xhrComplete',
        response: ...
    }
    

    Now your timer can listen for actions of type pageLoad and start/stop itself based on whether or not the page being loaded requires a timer.