Ela
Ela

Reputation: 57

What is the best way of fetching data from server in Meteorjs?

I am making simple application where user can add some data in the website. Every time, when user adds new 'name' I want display the latest name automatically for every connected users. I am not sure if my implementation of Template.names.name is a good idea, maybe I should use subscribe instead?

Here is my code:

<template name="names">
    <p>What is your name ?</p>
    <input type="text" id="newName"/>
    <input type="button" id="nameSubmit" value="add new"/>

    <p>Your name: {{name}}</p>
</template>

if (Meteor.isClient) {
    Template.names.name({
        'click input#nameSubmit': function () {
            Meteor.call('newName', document.getElementById("newName").value);
        }
    });

    Template.names.name = function () {
        var obj = Names.find({}, {sort: {"date": -1}}).fetch()[0];

        return obj.name;
    };
}

if (Meteor.isServer) {
    newName: function (doc) {
        var id = Names.insert({
            'name': doc,
            'date': new Date()
        });

        return id;
    }
}

I use meteorjs version 0.8.1.1.

Upvotes: 0

Views: 92

Answers (1)

Kelly Copley
Kelly Copley

Reputation: 3158

The only thing I see inherently wrong with your code is your method.. To define methods you can use with Meteor.call you have you create them with a call to Meteor.methods

Meteor.methods({
    newName: function (name) {
        Names.insert({
            'name': doc,
            'date': new Date()
        });
    }
});

Another couple notes.. The Method should be defined in shared space, not just on the server unless there is some specific reason. That why it will be simulated on the client and produce proper latency compensation.

Also in your Template.names.name you can return the result of a findOne instead of using a fetch() on the cursor.

Template.names.name = function () {
    return Names.findOne({}, {sort: {"date": -1}}).name;
};

Upvotes: 1

Related Questions