javascriptreactjsmeteormeteor-react

Why does my function on the server return true but returns false on the client side in Meteor.js


I have hasCompleted function that returns true or false which is in the server file file:

Smaples.helpers({
 hasCompleted(userId) {
    // …
    switch (this.frequency) {
      case Frequency.ONE_TIME:{
        return measures.fetch().every(measure => {

          console.log(
            'measure.hasCompleted(userId)', //  true
            measure.hasCompleted(userId),
          );

          measure.hasCompleted(userId);
        });
      }
    }
   // …
  },
})

But when it comes to the client side the above function returns false.

On the client side using useTracker:

  const hasCompleted = useTracker(
    () => sample.hasCompleted(Meteor.myFunctions.getCurrentUserId()),
  );
  console.log(
    'survey.hasCompleted(Meteor.myFunctions.getCurrentUserId())', // false
    survey.hasCompleted(Meteor.myFunctions.getCurrentUserId()),
  );
  console.log('hasCompleted', hasCompleted); // false

The way I access helpers from the client side, is this wrong?

Attempts

inside hasCompleted I manually return true and the console shows true:

Smaples.helpers({
 hasCompleted(userId) {
    // …
    switch (this.frequency) {
      case Frequency.ONE_TIME:{
        return true; // changed
    }
   // …
  },
})

Also, I thought if

console.log(measure.hasCompleted(userId))

after returning it could be changed, but

console.log(measure.hasCompleted(userId))

still returns true:

Smaples.helpers({
 hasCompleted(userId) {
    // …
    switch (this.frequency) {
      case Frequency.ONE_TIME:{
        return measures.fetch().every(measure => {
          measure.hasCompleted(userId);
          console.log(
            'measure.hasCompleted(userId)', //  true
            measure.hasCompleted(userId),
          );
        });
      }
    }
   // …
  },
})

What am I doing wrong?


Solution

  • You very probably just miss a return in the callback of your measures.every() call:

    Array.prototype.every doc:

    true if the callbackFn function returns a truthy value for every array element. Otherwise, false.

    Smaples.helpers({
     hasCompleted(userId) {
        // …
        switch (this.frequency) {
          case Frequency.ONE_TIME:{
            return measures.fetch().every(measure => {
    
              console.log(
                'measure.hasCompleted(userId)', //  true
                measure.hasCompleted(userId),
              );
    
              // Make sure to return a truthy value if the item passes your condition
              return measure.hasCompleted(userId);
            });
          }
        }
       // …
      },
    })
    

    Note: in case your array is empty (no documents), every always returns true; be careful if this is not what you want.

    Not sure about your Server part since there is no information about it.