Search code examples
reactjsreactjs-flux

Reactjs with Flux: when and where to initialize a Timer utility in a Flux application


I have three different things going on in my application:

  1. A Timer is set at 10 second intervals and does't stop until asked to
  2. An async Api Utility module triggers a function to call an Api once the timer starts over again.
  3. I have a Component (w/ accompanying Action and Store modules) that takes the api data (a list of similar items with the same Properties) and renders them to the page.

My question is this:

Where and When do I initialize the timer to being so that my Component can start receiving data after its render() method is invoked?


I've considered putting it inside the render function before the return is reached but that doesn't make sense as I need the api data rendered to the page as soon as the data is received.

Am I structuring this application incorrectly? should my Timer and/or Api utilities be React Components too?


Solution

  • I am sure there are a few ways to it, but here is my 2 cents:

    Lets assume you have LogViewer application and you want to fetch and display logs every 10 seconds.

    • Then you would have a LogStore and a LogViewer component.
    • In the componentDidMount method of the LogViewer component, I would call LogStore.getLogs().
    • LogStore.getLogs() would call APIUtils.getLogs() and setup a timer to be fired every 10 seconds which calls APIUtils.getLogs() every time it is fired. After setting the timer LogStore.getLogs() immediately returns an empty array.
    • The empty array is rendered by the LogViewer component (or a loading bar is shown).
    • Meanwhile, the ajax call from APIUtils.getLogs() returns and GET_LOGS_SUCCESS server action is dispatched to all stores.
    • LogStore saves the incoming logs and emits a change event for the LogViewer component to call LogStore.getLogs() function again.
    • If at some point you want to stop the timer, then in the LogViewer component I would have a stop button which in turn creates GET_LOGS_STOP action when clicked.
    • When GET_LOGS_STOP action is dispatched to the LogStore, it would react by stoping the timer.

    I think that would fulfill your requirements.