[Worked Around Solved] getMeteorData() is slow

In general, in Meteor, we’ve gotta be careful info we want to be reactive. If we use Meteor.user() in a computation, then that will be reactive when absolutely any info inside the user object changes, which can be lots if the user object has lots of changing info.

I read somewhere (can’t find it at the moment) that if you want to react to a specific property of a document, you can do just that with the fields option, which will cause reactive updates less often and perform better:

Meteor.users.findOne(id, {fields: {"profile.foo": 1}}) // react only to changes on profile.foo

Additionally, we can throttle reactivity and limit it to, say, at most one update per 2-second time window:

let profileFoo = new ReactiveVar('') // initial value of empty string

let setProfileFoo = _.throttle(value => profileFoo.set(value), 2000)
                                     // ^ fire this logic at most once in any
                                     // given 2-second period of time.
                                     // See http://underscorejs.org/#throttle

Tracker.autorun(computation => {
    let foo = Meteor.users.findOne(id, {fields: {"profile.foo": 1}})
    setProfileFoo(foo)
})

class Foo extends React.Component {
    render() {
        // this render method will only fire at most once per 2 seconds.
    }
    getMeteorData() {

        // will only change at most once in any 2-second time window, and only on the profile.foo property!
        let foo = profileFoo.get()

        return {foo}
    }
}

This getMeteorData is “fast” now. :wink:

11 Likes