Sean L
Sean L

Reputation: 827

Meteor: How to make sure new session variable is updated from method before going to Router.go?

I have a method in which a user joins an existing game or creates a new game. Additionally, the id of the respective id is stored in an object and returned as per below:

Meteor.methods({
    newGame: function(gameQuestions) {
        var user = Meteor.user();
        var gameWaiting = GameCollection.findOne({players: {$size: 1}, active: false, current: true});
        var result = {};

        if (!gameWaiting) {
            var gameId = GameCollection.insert
            //.....
            result.id = gameId;

        } else {
            if (_.contains(gameWaiting.players, user._id)) 
                 //.....
                result.id = gameWaiting._id;
            } else {
                //......
                result.id = gameWaiting._id;

            }
        }
        return result
    },

On the client-side I have a button in which a user clicks new game and puts the ID returned by the method and puts it in a session variable. From there the router goes to the ID provided:

Template.loggedIn.events({
    "click #newGame": function() {
        var gameQuestions = Questions.find().fetch();
        Meteor.call('newGame', gameQuestions, function(err, data) {
            if (err)
                console.log(err);

            Session.set('uniqueId', data);
            console.log(data)

        });
        var gameId = Session.get('uniqueId').id;
        console.log(gameId);
        Router.go('gamePage', {_id: gameId});
    }
});

However, the session variable is saved as the OLD session variable and the router then goes to the wrong address. Here is the console from the above:

creating a new game, none available 
yKrSeeAfMh4ppXWJP 
Object {id: "AKXYbWcdJWfaXfo8C"}

Here is address and the actual game ID

http://localhost:3000/games/yKrSeeAfMh4ppXWJP
Current Game ID: AKXYbWcdJWfaXfo8C

How do I make sure that var gameId is updated with the new Id returned from the meteor method before proceeding to the route?

Upvotes: 1

Views: 72

Answers (1)

Kuba Wyrobek
Kuba Wyrobek

Reputation: 5273

You are trying to redirect user immediatelly after he clicked without waiting for data from server. Redirect user after information from server is received -> inside callback.

Template.loggedIn.events({
    "click #newGame": function() {
        var gameQuestions = Questions.find().fetch();
        Meteor.call('newGame', gameQuestions, function(err, data) {
            if (err)
                console.log(err);

            Session.set('uniqueId', data);
            console.log(data)
            var gameId = Session.get('uniqueId').id;
            Router.go('gamePage', {_id: gameId});
        });
    }
});

Upvotes: 1

Related Questions