Error encountered when simulating the effect of calling 'insertPlayerData' function: ReferenceError - currentUserId has not been defined

PlayerList = new Mongo.Collection('players');
UerAccounts = new Mongo.Collection('user');
if(Meteor.isClient){
Template.leaderboard.helpers({
     'player':function(){
         var currentUserId = Meteor.userId();
 return PlayerList.find({createdBy: currentUserId},{sort: {score: -1,name: 1}})
      },
     'selectedClass':function(){
 var playerId = this._id;
 var selectedPlayer = Session.get('selectedPlayer');
 if(playerId == selectedPlayer){
 return "selected"
        }
      },
      'showSelectedPlayer':function(){
         var selectedPlayer  = Session.get('selectedPlayer');
         return PlayerList.findOne(selectedPlayer)
      }        
});
Template.leaderboard.events({
     'click .player': function(){
 var playerId = this._id;
         Session.set('selectedPlayer', playerId);
      },
      'click .increment':function(){
         var selectedPlayer = Session.get('selectedPlayer');
         PlayerList.update(selectedPlayer,{$inc:{score: 5}});
      },
      'click .decrement':function(){
         var selectedPlayer = Session.get('selectedPlayer');
         PlayerList.update(selectedPlayer,{$inc:{score: -5}});
      },
      'click .remove':function(){
         var selectedPlayer = Session.get('selectedPlayer');
         PlayerList.remove(selectedPlayer);
      }  
});
Template.addPlayerForm.events({
      'submit form':function(event){
         event.preventDefault();
         var playerNameVar = event.target.playerName.value;
         Meteor.call('insertPlayerData');
      } 
});
      Meteor.subscribe('thePlayers');
      Meteor.methods({
'insertPlayerData': function(){
   var currentUserID = Meteor.userId();
   PlayerList.insert({
name:"David",
score:0,
createdBy:currentUserId
});
}
});
}
if(Meteor.isServer){
     Meteor.publish('thePlayers',function(){
       var currentUserId = this.userId;
       return PlayerList.find({createdBy: currentUserId})
});
}
<head>
    <title>Leaderboard</title>
</head>
<body>
    <h1>Leaderboard</h1>
    {{> leaderboard}}
    {{> loginButtons}}
</body>
<template name="leaderboard">
   
     <ul>
         {{#each player}}
         <li class="player {{selectedClass}}">{{name}}: {{score}}</li>
         {{/each}}
     </ul>
     <input type="button" class = "increment" value ="give five points">
     <input type="button" class = "decrement" value ="take five points">
     <input type="button" class = "remove" value="remove player">
   {{#if showSelectedPlayer}}
     <li>slected Player: {{showSelectedPlayer.name}}</li>
   {{/if}}
   {{> addPlayerForm}}
     
</template>
<template name="addPlayerForm">
   {{#if currentUser}}
      <form>
         <input type="text" name="playerName">
         <input type="submit" value="Add Player">
      </form>
   {{/if}}
</template>
     

I am just starting to explore meteor and learning about methods and security concerns. While testing my code, I encountered an error stating "Exception while simulating the effect of invoking 'insertPlayerData'. Reference Error: currentUserId is not defined.".

Answer №1

It is crucial that this Meteor method resides on the server and not the client. Additionally, don't forget to include a callback for the Meteor.call('insertPlayerData') statement. I have tidied up a few other areas such as ensuring that Meteor.subscribe is properly placed within the code structure.

Please find the revised code below (not tested):

PlayerList = new Mongo.Collection('players');
UserAccounts = new Mongo.Collection('user');

if (Meteor.isClient) {
  Template.leaderboard.onCreated(function () {
    this.subscribe('thePlayers');
  });

  Template.leaderboard.helpers({
    'player': function () {
      var currentUserId = Meteor.userId();
      return PlayerList.find({createdBy: currentUserId}, {
        sort: {
          score: -1,
          name: 1
        }
      })
    },
    'selectedClass': function () {
      var playerId = this._id;
      var selectedPlayer = Session.get('selectedPlayer');
      if (playerId == selectedPlayer) {
        return "selected"
      }
    },
    'showSelectedPlayer': function () {
      var selectedPlayer = Session.get('selectedPlayer');
      return PlayerList.findOne(selectedPlayer)
    }
  });

  Template.leaderboard.events({
    'click .player': function () {
      var playerId = this._id;
      Session.set('selectedPlayer', playerId);
    },
    'click .increment': function () {
      var selectedPlayer = Session.get('selectedPlayer');
      PlayerList.update(selectedPlayer, {$inc: {score: 5}});
    },
    'click .decrement': function () {
      var selectedPlayer = Session.get('selectedPlayer');
      PlayerList.update(selectedPlayer, {$inc: {score: -5}});
    },
    'click .remove': function () {
      var selectedPlayer = Session.get('selectedPlayer');
      PlayerList.remove(selectedPlayer);
    }
  });

  Template.addPlayerForm.events({
    'submit form': function (event) {
      event.preventDefault();
      var playerNameVar = event.target.playerName.value;
      Meteor.call('insertPlayerData', function (error, result) {
        // handle error/success
      });
    }
  });
}

if (Meteor.isServer) {
  Meteor.publish('thePlayers', function () {
    var currentUserId = this.userId;
    return PlayerList.find({createdBy: currentUserId})
  });

  Meteor.methods({
    'insertPlayerData': function () {
      var currentUserId = Meteor.userId();
      PlayerList.insert({
        name: "David",
        score: 0,
        createdBy: currentUserId
      });
      // error handling needed
      return {success: true};
    }
  });
}

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

Tips for swapping a component with another component in React.js without the need for a page refresh

class Navigation extends Component { constructor(props) { super(props); this.state = { width: window.innerWidth, } } updateWidth = () => { if (this.state.width > 700) { this.setStat ...

Tips for retrieving data from a JSON array

I have a JSON object that looks like this: var obj={ "address":{ "addlin1":"", "addlin2":"" }, "name":"sam", "score":[{"maths":"ten", "science":"two", "pass":false }] } Now, when I attempt to m ...

Fiddle demonstrates HTML functionality, while local testing is unsuccessful

Currently, I am in the process of creating an image slider and attempting to run it on my personal computer. However, upon doing so, I have encountered a problem where the page is not rendering correctly. Additionally, I receive an ActiveX warning message ...

Refresh Material-Ui's Selection Options

Is there a way to properly re-render the <option> </option> inside a Material UI select component? My goal is to transfer data from one object array to another using the Material UI select feature. {transferData.map(data => ( <option ...

Improving the efficiency of your if else code in React js

I am looking for a way to optimize my code using a switch statement instead of multiple if-else conditions. How can I achieve this? Here is the current version of my code: handleChange = (selectedkey) => { this.setState({ activeKey: selectedkey } ...

Click event not functioning in programmatically loaded HTML

I am facing an issue with a JSON file that contains the page content I am trying to load. The link within it appears as follows: <a data-ng-click='foo()'>Bar</a> When I load this page content into the HTML page: <p class="body" ...

What is the best way to retrieve a specific item from an array of objects stored in JSON format using React?

I have received a json file named data.json which contains multiple objects in an array. My goal is to extract the value of a specific key from each object. To achieve this, I am utilizing react redux to fetch these values and present them in a table forma ...

Tips for utilizing SSR data fetching in Next.js with Apollo Client

Trying to integrate the apollo-client with Next.js, I aim to fetch data within the getServerSideProps method. Let's consider having 2 components and one page- section.tsx represents component-1 const Section = () => { return ( <div& ...

Get a CSV file through EmberJs

I have been experimenting with various function calls, but I am unable to figure out how to initiate a CSV download in EmberJs. Below is the most recent code I have tried: let endpoint = '/api/foo/'; let options = { url: endpoint, type: ...

Cloud Function scheduler incorporating dynamic memory allocation control

I am currently working on setting up a scheduled function in Firebase Cloud Functions that interacts with third-party APIs. However, I am facing an issue with the memory limit being exceeded due to the large size of the data processed by this function. Al ...

Implementing Shader Effects around Mouse using Three.js

Could someone please share tips on how to add a shader effect around the mouse area using Three.js? I'm inspired by the homepage of this website: I'm eager to explore some leads or examples. Thank you in advance! ...

Unable to upload gathered email to Mailchimp mailing list through Nodejs and express API

Seeking guidance on integrating data collection with Mailchimp in a Nodejs backend project. I am currently working on an email signup list page where users input their first name, last name, and email. The HTML file contains fields named firstName, lastN ...

Issue encountered when attempting to retrieve elements within an HTA's IFrame

We are currently working on automating an Intranet site using HTA and JavaScript. To bypass the browser security settings, we have implemented an Iframe within the HTA itself instead of opening the site in a browser. Despite being able to successfully logi ...

React - Ensure useEffect is triggered only after state update

One of my components (ItemsIndex) is using a custom hook to fetch data from our API. However, the ItemsIndex's useEffect runs first, causing the DOM to not be filled with elements that could be scrolled into view. How can I make sure that the useItems ...

Transferring JavaScript to a different page using EJS

Feeling a little stuck here and could use some assistance. It seems like a simple issue, but I'm tired and could really use a fresh pair of eyes to take a look. I'm trying to pass the 'username' variable, but since I'm new to this ...

Logging out of Laravel after sending a POST request

I'm developing a laravel application that heavily relies on POST requests. One common type of request in my app looks like this: var classElements = document.querySelectorAll("tr.ui-selected td.filename"); var csrf = $('input[name=_token]') ...

Tips for making sure the Button component in material-ui consistently gives the same ID value for onClick events

Issue arises when trying to log the ID of the Button component, as it only logs correctly when clicked on the edges of the button (outside the containing class with the button label). This problem is not present in a regular JavaScript button where text is ...

Executing API request from local server for production environment

I recently deployed my application to Heroku using npm run build. However, I encountered an issue where the API calls made in Heroku production are pointing to my localhost. Can anyone provide guidance on how to resolve this? api_axios.js const axios = r ...

A JQuery function linked to the click event of the body element triggers another click event right away

$().ready(function(){ $("#move-to").click(function(){ $("body").bind("click",function(){ alert("foo"); }); }); }); Why do I receive an alert message of "foo" immediately after clicking on "move-to"? When I bind the " ...

JavaScript can sometimes present peculiar challenges when it comes to setting style attributes, especially when a DOCTYPE is

It seems like I am encountering an issue when trying to dynamically create and modify a <div> element using JavaScript. The problem arises when I use the XHTML 1 Transitional doctype. This is how I am generating the <div>: var newDiv = docume ...