简体   繁体   中英

Deps.autorun with Meteor.user() issue on firefox and IE

So I have this code here for auto-subscribing to the current game of a player

Deps.autorun ->
  Meteor.subscribe "game", Meteor.user().profile.game

But it only works on google chrome. Both firefox and IE shows errors saying that Meteor.user(...) is undefined.

Notice that when I type Meteor.user().profile.game directly in the console, it returns the current game id just well. So apparently, the issue is only with the code above for some reason. Also, the other Deps.autorun functions that depends on a Session works just fine. Thanks.

It's a race condition. You are assuming that the user is already logged in when the autorun executes. If he/she isn't, then Meteor.user() will return null . One solution is to just use a soak:

Tracker.autorun ->
  Meteor.subscribe 'game', Meteor.user()?.profile.game

But the publish function knows which user is trying to subscribe, so I'd argue that a better solution would be something like:

Tracker.autorun ->
  if Meteor.user()
    Meteor.subscribe 'game'

Note the check for Meteor.user() in the autorun will force it to rerun when the user logs in (this is also good for performance reasons). Then on the server you can do:

Meteor.publish 'game', ->
  user = Meteor.users.findOne @userId
  {game} = user.profile
  Games.find game

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM