martyjs / marty

A Javascript library for state management in React applications
http://martyjs.org
MIT License
1.09k stars 76 forks source link

Isomorphic applications #114

Closed jhollingworth closed 9 years ago

jhollingworth commented 9 years ago

Fixes #13

Getting the right context

createStore, createActionCreators, createStateSource can be thought of as just registration functions for a container. We will introduce Marty.createContext() which will allow us to create instances of all stores, action creators, state sources for a specific context.

var context = Marty.createContext();

Marty.renderToString(<Foo/>, context).then(function (html) {
  res.send(html);
});

All stores, action creators and state sources will have this.context which is the specific instance it refers to. The big problem here is that everything is a static in Marty so we need a way of referencing the instance of store/action creator/state source for the context. We get around this by making stores, action creators and state sources functions. All ActionCreators, StateSources and Stores will have this.use(...) which resolve the correct instance of the object for the context. If you invoke the function with an object that has the context then it will return the relevant instance for that context

var FooStore = Marty.createStore({
  getFoo: function (id) {
    return this.fetch({
      id: id,
      locally: function () {
        return this.state[id];
      },
      remotely: function () {
        return this.use(FooAPI).getFoo(id);
        // instead of
        return FooAPI.getFoo(id);
      }
    })
  }
})

Waiting for state to be available

When you call Marty.renderToString, the view will try fire off a load of fetches to the store. By default we wait for all of those fetches to finish before resolving the promise. You will be able to configure timeouts, fetches to ignore, etc both globally and on a store/fetch basis.

State sources

For local & session storage we will not do anything. Same goes for socket.io. For HTTP:

oliverwoodings commented 9 years ago

Is there a way for us to give a warning if something isn't using contexts correctly? i.e. if someone does:

FooApi.getFoo(id)

instead of

FooApi(ctx).getFoo(id)

Otherwise I envision people getting a bit confused

jhollingworth commented 9 years ago

Good idea! I will add a warning if you're not using a context instance when running in node.js