kadirahq / flow-router

Carefully Designed Client Side Router for Meteor
MIT License
1.09k stars 194 forks source link

[SSR] Watch out for code order between `find()` and `subscribe()` #534

Closed SachaG closed 8 years ago

SachaG commented 8 years ago

I just ran into a subtle bug with SSR, it's not really an issue but I thought I'd make a note of it in case somebody else has the same problem.

On the client (inside a reactive context such as getMeteorData()), both of these do basically the same thing:

Meteor.subscribe("myPublication");
const data = Posts.find().fetch();
return {posts: data};

and

const data = Posts.find().fetch();
Meteor.subscribe("myPublication");
return {posts: data};

Since the context is reactive, it doesn't matter if you do the find().fetch() first or subscribe first, because find().fetch() will rerun a second time once the subscription is ready anyway.

But when running on the server the order does matter! If you call fetch() before subscribe(), there won't be any data in Posts (since FlowRouter SSR only makes available data that you've “published” to simulate the client's state) and fetch() will return an empty array.

So make sure to always subscribe first.

arunoda commented 8 years ago

Yeah! This is not a bug anyway :) I think your PR to the README will address this.