0

I'm trying to figure out the best way to dynamically select a component and store based on the data my server receives. The app is based on these examples: https://github.com/yahoo/flux-examples/tree/master/fluxible-router but a little different:

  1. User goes to mysite.com/that/and/that (the app can't know what type of thing 'that/and/that' is, so this can't be handled in the routing).
  2. Server does a GET request to our CMS. The CMS returns the data, including what type of data it is (section listing, article, company profile, etc.)
  3. Here I can dynamically select a component like so (this is in the render method of a parent component for now):

    switch (this.props.documentType) { // From the CMS
        case 'Section':
            Handler = require('../section/section');
            break;
        case 'Article':
            Handler = require('../article/article');
            break;
        default:
            // Do nothing
    }
    

All good. But I also want to put my data in a particular store. What is the best way to do that? Some ideas that seem a little hacky to me:

  1. In this same switch statement, dynamically execute an action to send data to the appropriate store, the 'article' component will rely on the 'article' store having data.

  2. Send the data to the component itself and let (for example) the article component initialize the article store with that data.

  3. Actually put the document type in the URL, e.g. mysite.com/article/this/and/that and handle all this neatly in the routes. But I'd rather not mess up my URLs just because I couldn't work out an elegant solution :)

Thanks in advance for any ideas.

David Gilbertson
  • 4,219
  • 1
  • 26
  • 32

1 Answers1

1

This is an unfortunate limitation of having React rendering be completely synchronous on the server: decisions about which components to render happen too late for you to load the data ahead of time. For this reason, we have frequently moved that decision of which component to render outside of the parent component, and instead make the mapping static (via configuration) or a separate method that gets executed by an action. In this way, the action calls the function or checks that static map, figures out which one will be used, and calls another action to fetch the data. Then the action can dispatch the data and the component to be used to the store. The component then gets the child from the store and renders it dynamically.

It's not an ideal solution and it probably violates some Flux principles, but it's the only thing that we have found that lets us dynamically load components on the server correctly.

Michael Ridgway
  • 5,259
  • 1
  • 16
  • 6