javascriptnode.jsmeteormeteor-accountsaccounts

Meteor template gets created twice, after adding accounts-ui package


I started to learn meteor and i did setup a small test project. I made a simple template like so test.html:

<head>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>Test</title>

</head>
<body>

 {{> TestPage}}

</body>
<template name="TestPage">
    <p>hello</p>
</template>

I also installed iron-router and i tried did setup the routes. Then i checked with meteor run, and everything was ok, i got a plain page with one hello text sign. After that i wanted to try and make simple login page, i added meteor add accounts-ui accounts-password. After that, when i tried to load my page, the hello displayed twice. So i went to the js part to try and understand what is going on. Here is full test.js:

var textMessage = "";
var textMessageDep = new Deps.Dependency;

var getTextMessage = function()
{
    textMessageDep.depend();
    return textMessage;
};
var setTextMessage = function (newValue) {
    if (newValue !== textMessage)
        textMessageDep.changed();
    textMessage = newValue;
};
Template.TestPage.onRendered(function () {
   console.log('on rendered');
});
Template.TestPage.onCreated(function () {
    console.log('on created');
});

So from that, i managed to get the following output in js console:

on created
on created
on rendered

On created event is called two times for some reason, that's why i get two copies of template rendered. How to correctly overcome this issue? I assume meteor waits for Meteor.Users collection to get ready? I didn't even add any users to this collection.

Also this is how my router config looks like:

Router.map(function() {
    this.route('/', {
        onBeforeAction: function () {
        // here planned to add 
        // if(!Meteor.user()) {}
        // 
               this.render('TestPage'); 
        }

    });
});

Solution

  • It is because you asked Meteor to render the template twice. By default, meteor will load any file with the body tag first, which is the one you put TestPage template at this moment. Then you put into the onBeforeAction another rendering for the TestPage, therefore, another TestPage appears on page. One way to solve this is removing the one in the onBeforeAction

    The correct way specify the template to render in the router is

    this.route('TestPage', {
        path: '/'
    });
    

    and remove the one in the body