react-router icon indicating copy to clipboard operation
react-router copied to clipboard

Proposal: Replace AsyncState with getAsyncProps

Open mjackson opened this issue 12 years ago • 107 comments

Edit: Please read my updated proposal as well

I'd like to propose adding two new transition hooks, didTransitionTo and didTransitionFrom that are designed to replace the AsyncState mixin. Currently, AsyncState has the following quirks/limitations:

  • It keeps data in this.state, but data is passed passed to children through props in render
  • It's a mixin but it was only ever intended to be used in route handler components, so users may be inclined to use it in other components (which we don't support). Also, it means that users need to declare the mixin

The goals for these two new transition hooks are:

  • Keep data in props, where it belongs. this.state should be used for UI state
  • Keep the ability for components to subscribe to changes in data, but also have a way to let components know that data only needs to be fetched once (for server rendering)
  • Keep the ability for components to fetch data in parallel
  • More clearly indicate that data fetching behavior belongs in route handlers, and not other components and eliminate the need for users to declare a mixin in order to use it

I believe the following API satisfies all of the above requirements. Feedback is welcome.

var User = React.createClass({

  statics: {

    // This hook is called after the transition has been validated by all
    // willTransition* hooks. The setProps argument is a function that
    // can be used to set props ad hoc (like AsyncState's setState).
    didTransitionTo: function (params, query, singleRun, setProps) {
      // If you have an immediate value, use it.
      setProps({ user: UserStore.getUserByID(params.userID) });

      // If we're not on the server, subscribe to changes in the data.
      if (!singleRun) {
        this.userListener = function () {
          setProps({ user: UserStore.getUserByID(params.userID) });
        };

        UserStore.addChangeListener(this.userListener);
      }

      // Or, ignore setProps entirely and return a hash of values that should
      // be used as props. Values may be immediate or promises. As they
      // resolve, props are updated.
      return {
        user: fetchUser(params.userID)
      };
    },

    // This hook is called after the transition has been validated by all
    // willTransition* hooks.
    didTransitionFrom: function () {
      UserStore.removeChangeListener(this.userListener);
    }

  },

  // The render method needs to be resilient to the fact that props
  // may not yet be loaded.
  render: function () {
    var user = this.props.user;
    var name = user == null ? 'anonymous' : user.name;

    return <div className="user-component">Hello {name}!</div>;
  }

});

Note that, although this API looks similar to the willTransition* API, it has two key differences:

  • handlers are run in parallel, not in sequence, so all data can be fetched at the same time
  • the resolution of these handlers does not block the transition from happening

Thanks to @rpflorence for giving me feedback and helping me think through this API earlier today!

Edit: Updated example code to make setProps the last (optional) argument to didTransitionTo.

mjackson avatar Sep 03 '14 21:09 mjackson

:thumbsup:

if (!singleRun) {
  this.userListener = function () {
    setProps({ user: UserStore.getUserByID(params.userID) });
  };

  UserStore.addChangeListener(this.userListener);
}

Looks sorta bleh, but it could easily be wrapped up and made declarative based on the architecture of an individual application, like mapping async props to stores by key with a mixin etc.

// I dunno, something like this would totally be possible
var SomeHandler = React.createClass({
  mixin: [FluxBBQ({
    users: UserStore,
    assignments: AssignmentStore
  })]
});

Good that the router doesn't get too interested in application conventions.

ryanflorence avatar Sep 03 '14 22:09 ryanflorence

I almost wrote it like:

        UserStore.addChangeListener(this.userListener = function () {
          setProps({ user: UserStore.getUserByID(params.userID) });
        });

A little more concise :) But yeah, the router needs to be pretty generic so your app can do whatever it wants.

mjackson avatar Sep 03 '14 22:09 mjackson

Do you mean AsyncState? I'm not seeing what this has to do with ActiveState.

ewiner avatar Sep 03 '14 22:09 ewiner

@ewiner Yes, thanks for pointing that out. My brain is fried from thinking about this too much..

mjackson avatar Sep 03 '14 23:09 mjackson

I wouldn't mind supporting the use cases described in #176, namely, leaving the previous screen rendered while these transition hooks resolved, via an option on <Route/> perhaps.

ryanflorence avatar Sep 03 '14 23:09 ryanflorence

@rpflorence Interesting. So basically just a flag that gives you fine grained control over when you actually want things to update?

The way I see it there are two options:

  1. after willTransition* hooks resolve (this is what we currently do)
  2. after didTransition* hooks resolve

What's the main use case for the second? To prevent flickering while data loads? What about the delay in navigation?

mjackson avatar Sep 03 '14 23:09 mjackson

The setProps callback you have is weird to me. State is a fine place to store data that comes from a store – I feel that the biggest difference between props and state is where it comes from, not model state vs. UI state or anything like that.

sophiebits avatar Sep 04 '14 00:09 sophiebits

I'm indifferent about props vs. state and like avoiding needing to declare a mixin.

KyleAMathews avatar Sep 04 '14 00:09 KyleAMathews

Why is there a didTransitionFrom? How is it different from componentWillUnmount?

KyleAMathews avatar Sep 04 '14 00:09 KyleAMathews

(setProps sounds confusingly similar to this.setProps which you can't and shouldn't call on yourself.)

sophiebits avatar Sep 04 '14 00:09 sophiebits

@spicyj setProps is the props equivalent of AsyncState's setState function, which I believe also was a little weird to you when I first introduced it :)

The important thing to note is that you don't actually have to use it. In fact, it should probably be the last argument to didTransitionTo. The only reason it exists is to support the streaming data use case. We could omit the argument entirely if we don't want to support streaming.

The way the router is built, all data is passed in as props (think params, query, etc.). The setProps argument is just a way to add to those.

mjackson avatar Sep 04 '14 00:09 mjackson

@KyleAMathews didTransitionFrom is specific to the router. It doesn't care about mounting. It's really just the logical compliment to didTransitionTo with slightly different semantics from componentWillUnmount.

Up to this point people have been using componentDidMount and componentWillUnmount as a hack for loading/unloading data. This commit addresses that.

mjackson avatar Sep 04 '14 00:09 mjackson

didTransitionTo also sounds like an odd place to do data-fetching – I would expect it to get called after data is fetched, not before.

sophiebits avatar Sep 04 '14 00:09 sophiebits

I just picked these names because they correlate directly with the willTransition methods. If you have better suggestions, I'd love to hear them.

mjackson avatar Sep 04 '14 00:09 mjackson

@rpflorence BTW, I should mention that it would be trivial to implement #176 using the architecture I've got going (been hacking on this today). Just kind of seems like a footgun.

mjackson avatar Sep 04 '14 01:09 mjackson

I think it's valid. Lots of apps do this and it feels fine. Gmail, google analytics, some parts of Facebook, even some native iPhone apps I use.

Sent from my iPhone

On Sep 3, 2014, at 7:01 PM, Michael Jackson [email protected] wrote:

@rpflorence BTW, I should mention that it would be trivial to implement #176 using the architecture I've got going (been hacking on this today). Just kind of seems like a footgun.

— Reply to this email directly or view it on GitHub.

ryanflorence avatar Sep 04 '14 02:09 ryanflorence

@rpflorence ok. Let's discuss in a separate issue.

mjackson avatar Sep 04 '14 02:09 mjackson

In React's core API, the will* and did* methods are intended for doing side effect operations with no return value before or after some built-in action, while the get* methods are intended for you to return some data that the library will then use.

didTransitionFrom() seems like more of the former case, while didTransitionTo() is the latter. I would suggest ditching the parallelism with the willTransition methods and name them following the core API's naming pattern, maybe something like:

  • getPropsAsync instead of didTransitionTo
  • componentDidTransitionAway instead of didTransitionFrom

I didn't suggest getInitialPropsAsync or getDefaultPropsAsync because the props are neither initial nor default. And I feel much less strongly about the didTransitionFrom name, because like @KyleAMathews I don't quite understand the intended use of it yet.

ewiner avatar Sep 04 '14 04:09 ewiner

didTransitionFrom is a spot to remove change listeners on stores.

I like @ewiner's names.

ryanflorence avatar Sep 04 '14 04:09 ryanflorence

(though, willTransitionFrom is as good a place as any for that ...)

ryanflorence avatar Sep 04 '14 04:09 ryanflorence