Upon redirection, the Meteor session becomes unrecognizable

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');
}

Answer №1

As per the guidelines outlined in the Meteor API documentation, Meteor methods are primarily intended for defining server-side functionalities that can be invoked from the client side. It is recommended to define these methods on the server for proper execution.

Meteor methods serve as remote functions that clients can trigger using Meteor.call.

If a Meteor method is defined on the client side, it essentially acts as a placeholder.

Invoking methods on the client creates stub functions linked with server methods of the same name.

Based on the code provided, it appears that all operations are being performed on the client side. Notably, the session feature belongs to the Meteor client API and cannot be utilized on the server.

The Session feature offers a global object on the client side for storing various key-value pairs.

Therefore, I would suggest consolidating this logic in a utility file that can be imported into relevant Templates where needed. Essentially, you are accomplishing the same tasks but using regular functions instead of Meteor methods.

Below is an example utility file (adjust the Players import based on your project's structure).

import { Players } from './players.js';
import { Session } from 'meteor/session';

export const players = {
  insert: function(code, name) {
    console.log('Adding player: ', name , code);
    return Players.insert({code: code, name: name});
  },

  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]}});
    }
  },

  setCurrent: function(playerId) {
    Session.set("currentPlayer", playerId);
    console.log(Session.get("currentPlayer"));
  },

  getCurrent: function() {
    return Session.get("currentPlayer");
  },
};

You can then import this into the respective template containing the event handler mentioned in your query.

import { Template } from 'meteor/templating';
import { players } from './utils.js';

Template.template_name.events({
  'click .class': handleSubmit (event, instance) {
    event.preventDefault();
    var party = Players.findOne({code: this.refs.code.value});

    if (typeof party !== 'undefined') {
        var playerId = players.insert(this.refs.code.value, this.refs.name.value);
        players.setCurrent(playerId);
        location.href = "/" + this.refs.code.value;
    } else {
        document.getElementById("error").innerHTML = 'Please enter a valid party code';
    }
  },
});

Remember to customize the code snippet above according to your actual template name and utility file location.

Answer №2

It seems like the issue may be related to the way you are implementing it.

location.href = "/" + this.refs.code.value;

Consider using the following instead:

Router.go("/"+this.refs.code.value);

If you are working with Iron Router, using the correct syntax is crucial. Otherwise, it can lead to unexpected behavior like refreshing the page. You might also find this package useful for maintaining Session variables even after page refreshes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to describe duplicate keys within a JSON array?

I have created a specialized program to extract Dungeons and Dragons data from JSON files. While the main functionality is complete, I am struggling with defining unique keys for multiple attack options without manually assigning individual identifiers. H ...

Performing a JSON AJAX call that sends a null object to a Java class

Within my JavaScript file, I am utilizing the following getJSON method like so: $.getJSON('do/ajax-convertlocaldatetime', { timestamp : localdatetime, The localdatetime variable is an instance of a LocalDateTime object. This ajax call trigg ...

Showing arbitrary text on Vue.js template

In my Vue.js application, I have a Loader component that randomly displays one of several messages. Here is how I implemented it: Vue.component('Loader', { data() { const textEntries = [ 'Just a moment', ...

How to modify a nested object in MongoDB based on the JSON data provided

In my possession, there exists a structured form of JSON data as displayed below: [ {"size":100,"year":2015,"geography":"London","age":"21","gender":"Female"}, {"size":80,"year":2015,"geography":"Cardiff","age":"38","gender":"Male"}, {"size":80,"year":201 ...

The addEventListener function seems to be malfunctioning in the React JS component

Initially, the program runs correctly. However, after pressing the sum or minus button, the function fails to execute. componentDidMount() { if(CONST.INTRO) { this.showIntro(); // display popup with next and previous buttons let plus = docume ...

Stop event bubbling in Vue.js for router link

I'm working with the following HTML template... <template> <li class="nav-item" style="z-index:9"> <router-link :to="link.path" @click.native="linkClick" ...

Efficiently uploading numerous SVGs in vue.js using vue-svg-loader

Is there a more efficient way to import multiple SVGs in a Vue component without having to individually import each one as suggested in the documentation? Check out vue-svg-loader documentation: <script> import Info from "@/assets/svgs/info.svg"; ...

What is the best way to create a TextGeometry object with multiple lines? Is there a way to contain it within a square shape, similar to how text wraps within a div

I've been experimenting with creating 3D text using WebGL, three.js, and THREE.TextGeometry. So far, everything is working smoothly as I'm able to generate a single line of 3D text. Now, my goal is to produce multiline text resembling a short pa ...

Trouble with combining Mongoose's $slice and select operations in a query

Every time I try to use const data = await User .findOne() .slice("followers", 10) .select("followers") .exec() console.log(data) I keep running into an issue where the slice and select methods don't seem to work together. Indiv ...

Listening for time events with JQuery and controlling start/stop operations

I recently developed a jQuery plugin. var timer = $.timer(function() { refreshDashboard(); }); timer.set({ time : 10000, autostart : true }); The plugin triggers the refreshDashboard(); function every 10 seconds. Now, I need to halt the timer for ...

Retrieve a subsection of an object array based on a specified condition

How can I extract names from this dataset where the status is marked as completed? I have retrieved this information from an API and I need to store the names in a state specifically for those with a completed status. "data": [ { "st ...

The TypeScript fs/promises API is experiencing compilation issues when used in JavaScript

While working with TypeScript and the fs/promises API, I encountered an error when compiling and running the TypeScript code. The error message displayed: internal/modules/cjs/loader.js:968 throw err; ^ Error: Cannot find module 'fs/promises' ...

How can I embed an iframe in an Angular 4 application?

I'm facing an issue with my Angular 2 v4 application where I have the following code snippet: <iframe src="https://www.w3schools.com" style="width: 100%; height: 500px"></iframe> However, the iframe does not seem to work. I attempted to ...

Guide to finding the alert tag element within the outer div container

When trying to locate elements on this particular page and place them in Objects (DomElement) for testing purposes, I encountered an issue with the reg-error-yid element. This element is nested inside the yid-field-suggestion div, and despite my attempts t ...

My App Router is unable to retrieve data from my Express API, which is running on localhost but on a different port

I've been struggling for a full day to make a fetch call to my backend API work without success. Below is the snippet from my page.js: export default async function Page() { //const response = await fetch('https://api.github.com/repos/vercel/n ...

Troubleshooting: Issue with Evaluating Whitespaces in MongoDB using Bash

When working with a bash script, you may encounter the error message Unexpected token ILLEGAL #!/bin/bash value="White Spaced String" mongo --verbose localhost:27017/myDB --eval 'db.ips.update({"id":"id"}, { $push: { "key": {"key":"'$value' ...

Separate an array into equal parts according to integer values in JavaScript

Although I have not come across any questions that address my specific issue, it may be a duplicate. Imagine having an array similar to this: var hundred = [1,2,3,4,5...100] This particular array consists of 100 elements, ranging from 1 to 100. Given ...

Tips on adding additional features to Tween.js library (https://github.com/sole/tween.js/)

Currently, I am in the process of tweening between two values, unsure if they will involve position or scale. To handle this uncertainty, I have set up a Tween with an if statement within the update loop. if( params.type == 'position' ){ init ...

Performing a GET call within the configuration settings of AngularJS

I found a similar question here but unfortunately it didn't solve my issue. I am currently using Angular-UI's Google Maps API, which requires configuration as follows: .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider ...

Issue with Nav Bar Toggle not changing text to white color

Query I'm baffled as to why the text in the navigation bar (when opened with the Burger Menu) refuses to turn white. I've exhausted all efforts to change the color to white. Please assist me in pinpointing why the text remains unaffected when t ...