title: How to handle long async operations in Next.js to avoid slow page loading?
body: <p>When using <code>next-redux-wrapper</code> how do I start a long asynchronous task so that it only runs on the client?  I don’t want to use <code>await</code> on the server side since it would delay the initial page load. I’d rather set a loading flag as the task starts and show a loading indicator until it completes. </p>
  
  <p>Let’s say my async operation looks like this:</p>
  
  <pre><code>function async takesLong(store) {
      store.dispatch({type: “LOADING”, payload: true});
      const result = await longOperation();  
      store.dispatch({type: “SETDATA”}, payload: data);
      return store.dispatch({type: “LOADING”, payload: false});
  }
  </code></pre>
  
  <p>I can call this in my Next page’s <code>getInitialProps</code> function like this:</p>
  
  <pre><code>MyPage.getInitialProps = async ({ store, isServer }) =&gt; {
    const loader = takesLong(store)
    if (isServer) await loader;   // &lt;-- will delay client response
    return {
      someprop: "some value"
    };
  };
  </code></pre>
  
  <p>This works well if the page loads on the <strong>client side</strong>. The operation starts, and my page can display a loading-spinner until the operation completes. But when started on the <strong>server side</strong> I have a long delay before the page displays at all.  I’ve tried a number of approaches but can’t find one that works properly:</p>
  
  <ol>
  <li>Starting the process on the server and not using <code>await</code> renders the page without the results being written to the store, so it has only set “loading” to true in the store and it never gets the data.</li>
  <li>Passing <code>store</code> in my <code>props</code> doesn’t work - it ends up being an empty object (<code>{ }</code>) in the client.</li>
  <li><p>Trying to run it inside my component doesn’t seem to work for a few reasons:</p>
  
  <p>a) I don’t have the <code>store</code> object accessible in the React Component (only in <code>getInitialProps</code> which won’t get called on the client).</p>
  
  <p>b) Even if I use actions instead of <code>store.dispatch</code> in the Component, when can I call it safely?  I can’t do it during <code>render</code> since it will change the Redux state, and <code>componentWillReceiveProps</code> won’t get called before the first client-side <code>render</code> </p></li>
  </ol>
  
  <p>Is there a well defined pattern for deferring a long operation to the client-side when using Next?</p>