I'm in the process of creating a game that involves a player lobby without requiring user accounts, similar to the game Spyfall. Utilizing Meteor Sessions helps me keep track of which players have joined the lobby so I can provide accurate data for each individual. The join.js component is responsible for capturing the lobby access code and the player's name, redirecting the user to the lobby afterwards. This component is located at route /join, while the lobbies are situated at route /:lobby. Below is the handleSubmit method from join.js that takes user input and inserts it into the players collection:
handleSubmit(event) {
event.preventDefault();
var party = Players.findOne({code: this.refs.code.value});
if(typeof party !== 'undefined') {
Meteor.call('players.insert', this.refs.code.value, this.refs.name.value);
var playerId = Players.findOne({"name": this.refs.name.value})._id;
Meteor.call('players.current', playerId);
location.href = "/" + this.refs.code.value;
} else {
document.getElementById("error").innerHTML = 'Please enter a valid party code';
}
Sessions are utilized within the Meteor.methods in the players.js collection to retrieve the current user.
import { Mongo } from 'meteor/mongo';
import { Session } from 'meteor/session';
Meteor.methods({
'players.insert': function(code, name) {
console.log('adding player: ', name , code);
Players.insert({code: code, name: name});
},
'players.updateAll': function(ids, characters, banners, countries, ancestors) {
for (var i = 0; i < characters.length; i++){
Players.update({_id: ids[i]}, {$set: {character: characters[i], banner: banners[i], country: countries[i], ancestor: ancestors[i]},});
}
},
'players.current': function(playerId) {
Session.set("currentPlayer", playerId);
console.log(Session.get("currentPlayer"));
},
'players.getCurrent': function() {
return Session.get("currentPlayer");
}
});
export const Players = new Mongo.Collection('players');
The console.log
within the 'players.current'
method correctly returns the player id, but once redirected to /:lobby, the players.getCurrent
now shows as undefined. I aim to have players.getCurrent
display the same value as the console.log
. How can I address this issue? Here is the function used to obtain the current player id in lobby.js:
getCurrentPlayerId() {
return Meteor.call('players.getCurrent');
}