npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

reflux-preload

v2.2.1

Published

A way to manage preloading on the server within a reflux based application.

Downloads

8

Readme

reflux-preload

A way to manage preloading on the server within a reflux based application.

npm package build status dependency status

An architecture based on react-router and reflux has a chicken or egg dilemma problem. Where you need data to render your page on the server, but you don't know what data to load until you've rendered.

The problem is, Router yields a basic, static schematic of your app that is largely incomplete because child components are unknown till render, and because you're likely rendering "sorry, no content" rather than proper children when your components don't have data. Your data load itself isn't triggered to load though until Reflux Actions are fired, and those are likely fired until at least componentWillMount.

So, how do we resolve this? How about rendering again? You just need a promise that all your data is ready this time around. Enter "Reflux Preload", our idea is capture these data promises during the initial render, and then await those promises before rendering again. Along the way, we solve for:

  • Concurrent requests, that is we need to keep sets of promises separated from each other)
  • Passing data to client, so client-side React can pick-up where server-side left off.

Overview of Reflux Preload phases

  1. Render blank-slate on the server
  • During render: initiate loading reources, collect promises and recepient listeners.
  • We do not have usable data yet, provided later.
  1. Render with data on the server
  • Deliver the resources to registered listeners.
  • Render while skipping the load of additional resources.
  • Yield up a string for another layer to delier to client.
  1. Initial page load on the browser
  • Deliver the resources to registered listeners.
  • Render while skipping the load of additional resources.
  1. Secondary page load on the browser
  • Perform the load action as normal flow of loading component.

Integration

  1. Assumptions
  • You're using react-router in addition to reflux.
  • You have a means of converting your data requests to Promises - we're using axios.
  • You're accustomed to Reflux's async Actions using the listenAndPromise method.
var GetWikiActions = {};
GetWikiActions.load = Reflux.createAction({asyncResult: true});
GetWikiActions.load.listenAndPromise(function(titles) {
  return axios.get("http://en.wikipedia.org/w/api.php", {
    "titles": titles,
    "action": "query",
    "format": "json",
    "continue": ""
  });
});
  1. Components

In your component, you'll add a Preload.connect which binds an async Actions to a key in the Preload object. This key should be unique to your needs, typically we just use the Action name.

var WikiList = React.createClass({
  mixins: [
    Router.State,
    Reflux.connect(WikiStore, 'wiki'),
    Preload.connect('GetWiki', GetWiki.load),
  ],
  contextTypes: {
    router: React.PropTypes.func
  },
  // Preload hook: Fires loading action and a promise of data.
  preload: function () {
    return GetPages.load(this.context.router.getCurrentParams());
  },
  // Checks to see if loading is needed on client-side.
  isLoaded: function () {
    return this.state.wiki.query === this.getParams().query;
  },
  render: function () {
    return <ul>
      {_.mapValues(this.state.wiki.pages, page =>
         <li><a href={'http://en.wikipedia.org/wiki/' + page.title}>
           {page.pageid} : {page.title}
         </a></li>
      )}
    </ul>
  }
});

If you would prefer to avoid Mixins, you can call the methods directly.

Preload.receiveAction('GetWiki', GetWiki.load);
var WikiList = React.createClass({
  mixins: [
    Router.State,
    Reflux.connect(WikiStore, 'wiki'),
  ],
  contextTypes: {
    router: React.PropTypes.func
  },
  componentWillMount: function () {
    // Server: Always preload
    if (typeof window === "undefined") {
      Preload.promise(name, function () {
        return GetPages.load(this.context.router.getCurrentParams());
      });
    }
    // Client: Check if Preload if needed
    else if (this.state.wiki.query === this.getParams().query) {
      GetPages.load(this.context.router.getCurrentParams());
    }
  },
  render: function () {
    return <ul>
      {_.mapValues(this.state.wiki.pages, page =>
         <li><a href={'http://en.wikipedia.org/wiki/' + page.title}>
           {page.pageid} : {page.title}
         </a></li>
      )}
    </ul>
  }
});
  1. Server-side Renderer

Since, we do not know the tree in advance, we need to render twice. Once to collect any promises, and again to actually render. The module handles the double calls to render for you, you'll just need to wrap your normal render method.

  • Callback Style
function render (routes, url, callback) {
  Router.run(routes, url, function (Handler) {
    Preload.render(function myRenderMethod () {
      return React.renderToString(React.createElement(Handler));
    })
    .then(callback.bind(this, null), callack);
  });
}
  • Promise-Style
var prerender = Preload.render.bind(Preload, function render () {
  return '<div id="app">' +
    React.renderToString(React.createElement.apply(React, arguments)) +
    '</div>';
});
function render (routes, url) {
  return Promise(Router.run.bind(Router, routes, url))
    .then(prerender);
});
  1. Client-side Renderer

Be sure to deliver the payload before running React.

Preload.deliver();
Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(
    React.createElement(Handler),
    document.getElementById('app')
  );
});