Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginner Meteor: template and findOne

I want to try Meteor so I stated developing a small multi-rooms chat app in coffeescript. I am having problem passing the result of a findOne to html page using handlebars.

if Meteor.is_client
  room=Rooms.findOne({id:1})
  Template.room({room_name:room.name})

in the html page

 <head>
  <title>Chat!</title>
 </head>
 <body>
   {{> room}}
 </body>

<template name="room">
 Welcome to {{room_name}}
</template>

Now, given that the room document with id = 1 has name = 'Room1', I'd expect the page to render 'Welcome to Room1' but got a whitepage and the console shows 2 errors:

Uncaught TypeError: Cannot read property 'name' of undefined
Uncaught TypeError: Cannot read property 'room_name' of undefined

apparently room is undefined even if that document actually exists.

like image 791
dfucci Avatar asked Dec 07 '22 14:12

dfucci


1 Answers

It's undefined for a split second, before the client database cache has time to sync to the server. The template is supposed to render again once the client syncs, but since it threw an error the first time that won't happen (I was confused by a similar problem recently).

Try this (using short-circuit && to test that room exists):

if Meteor.is_client
    Template.room.room_name = ->
        room = Rooms.findOne({id:1})
        room && room.name

Note: I moved the findOne call into the function to make sure it gets called when updates happen, but it may have also been fine where you had it

like image 163
danny Avatar answered Jan 08 '23 15:01

danny