Errors in TypeScript are being brought up by using if-else statements inside a loop

I am currently working on a function to retrieve referral codes from users. The user inputs a code, which is then checked against the database to see if it exists or not

  1. If the code provided matches the current user's code, it should not be accepted as self-referrals are not allowed

  2. The code should match one of the codes stored in the database

However, I am facing an issue where even if the code exists in the database, the system fails to find a match. It works correctly when the referral code matches the current user's code and correctly points out that self-referrals are not permitted.

But in cases where the referral code matches another user's code, indicating a successful referral, the system still shows no match.

I need help in fixing this error

export const getID = functions.https.onCall(async(data, context) => {
  const db = admin.firestore();
  const usersSnapshot = await db.collection("user").get();
  const allUIDs = usersSnapshot.docs.map(doc => doc.data().userID);

  const userID = context.auth.uid;
  const providedID = "cNx7IuY6rZlR9mYSfb1hY7ROFY2";


 //db.collection("user").doc(providedID).collection("referrals").doc(userID);

  await check();

  function check() {
    let result;
    allUIDs.forEach(idFromDb => {
      if (providedID === idFromDb && (idFromDb === userID)) {
        result = "ownmatch";
      } else if (providedID === idFromDb && (idFromDb !== userID)) {
        result = "match";
      } else {
        result = "nomatch";
      }
    });
    return result;
  }

  if (check() === "match") {
    return {
      message: `Match Found`,
    };
  } else if (check() === "ownmatch") {
    return {
      message: `Sorry, you can't use your own invite code`,
    };
  } else {
    return {
      message: `No User with that ID`
    };
  }
});

Answer №1

(This code snippet is not an answer, but rather a simple refactoring suggestion.)

Here is an overview of what your current code is doing (roughly, as it wasn't tested):

const resultMsgs = {
  nomatch:  'No User With That ID',
  ownmatch: 'Sorry, you can\'t use your own invite code',
  match:    'Match Found',
}

function check(uids, providedId, userId) {
  let result

  uids.forEach(idFromDb => {
    if (providedId !== idFromDb) {
      result = 'nomatch'
      return
    }

    if (userID === idFromDb) {
      result = 'ownmatch'
      return
    }

    result = 'match'
  })

  return result
}

export const getID = functions
  .https
  .onCall(async (data, context) => {
    const userId     = context.auth.uid
    const providedId = 'cNx7IuY6rZlR9mYSfb1hY7ROFY2'

    const db   = admin.firestore()
    const user = await db.collection('user').get()
    const uids = user.docs.map(doc => doc.data().userId)

    const checkResult = check(uids, providedId, userId)
    return { message: resultMsgs[checkResult] }
  })

(I have removed the seemingly unnecessary database collection operation from the code.)

Your forEach loop iterates over all values in the uids array, but the result variable will only store the value from the last comparison. This may be correct, but:

  • If you are searching for any match, this approach may not be suitable.
  • If you are looking for all matches, then the current logic may not work as expected.
  • If you intend to match the last UUID, the current implementation achieves that, albeit in a somewhat unconventional manner.

Hence:

  • If you seek to find any matches, consider using an appropriate any function.
  • If you aim to identify all matches, explore utilizing an all function instead.
  • If your goal is to find the first match, a simpler approach would be to check the first element directly.
  • If you want to perform comparisons on the complete set of values, you might need to use map instead of forEach, and handle each comparison outcome accordingly based on your requirements.

In any case, I recommend breaking down your code into smaller, more organized chunks. This will enhance its readability and maintainability, making it easier to troubleshoot and modify when needed.

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

Customizing CoreUI column names in Vue

I am working with an array of item objects for a table. For example: [{ name: 'Sam', age: 24 }] Instead of using the default column names like age, I want to set custom field names. For instance, I want to display the column as Id instead of age ...

Is it possible to execute a function within an HTML page simply by clicking on it?

As someone who is new to the world of HTML, CSS, and JS, I'm currently facing a challenge: On my website's page1.html, I have implemented a feature that allows users to sort different articles on the page by selecting a sub-menu from the navigat ...

I successfully converted a d3 chart to a base64 image format and now I am looking to share it on Facebook using either client-side JavaScript or Angular

After generating a base64 image from a cool d3 chart, my next challenge is figuring out how to share it on Facebook using either client-side javascript or Angular. Any suggestions? ...

Google App Engine does not properly interpret PHP code when making AJAX requests

I am currently facing an issue with using AJAX request on Google App Engine. In my local development environment, everything works fine and the request is correctly interpreted. However, when I deploy the code to production, the AJAX request renders the co ...

Front-end procedural logic for increasing identification values

$scope.items.push({ "itemId": $scope.tabId + 1, "itemName" : itemName, }); Whenever I try to push the item, I always console.log($scope.itemId) but it remains the same without increasing. One way to handle this issue could be utilizing $http after each ...

Enforcing TypeScript restrictions on method chaining during object creation

Let's consider this unique sample class: class Unique { public one(): Pick<this, "two" | "three"> { return this; } public two(): Pick<this, "three"> { return this; } public three(): string { ...

Experiencing issues with overflowing columns in JQuery Datatables

I am currently facing an issue with my datatable where I need it to have a specific width while also displaying all its columns. The problem I am encountering can be summarized as follows: I came across solutions like Datatables Width Overflow For A ...

Saving the previous component's DOM in a React application

Understanding the Root.js File const Root = () => ( <HashRouter> <div> <Route exact path="/" component={Main}/> <Route path="/main/:page" component={Main}/> <Route path="/detail ...

Troubleshooting ECONNREFUSED in NextJS API: App successfully runs in both deploy and development mode, but encounters issues when next build is executed

Detailing the Glitch I've developed an application using NextJS that incorporates an internal API, utilizing the getStaticProps methods to interact with the API. You can access the live app at this link: Additionally, you can find the project' ...

Unable to maintain checkbox state after page reload in React

I am currently working on creating a to-do list application using React and Material UI. Everything is functioning well except for the checkbox state. I am storing each to-do as an object in an array called todoList in local storage, like this: todoList i ...

When using Vue with Vuetify, be aware that object literals can only specify known properties. In this case, the type 'vuetify' does not exist in the ComponentOptions of Vue with DefaultData

Started a fresh Vue project with TypeScript by following this guide: https://v2.vuejs.org/v2/guide/typescript.html If you don't have it installed yet, install Vue CLI using: npm install --global @vue/cli Create a new project and choose the "Manual ...

Variable unique to the specific function in universal function

Can you explain why the alert displays "AAA" instead of "BBB"? http://jsfiddle.net/Lp4cS/ var z = "AAA"; function xx() { var z = "BBB"; yy(); } function yy() { alert(z); } xx(); ...

Difficulty with replacing colors in an image on certain devices when using HTML5 Canvas

I have created a 2d RTS HTML5 / Javascript game that utilizes images to represent the player's units and buildings. To achieve different variations of these images with different colors, I use a script that replaces certain colors in the original imag ...

Seeking specific parameter in a JSON array using JavaScript: A guide

Currently, I am working on a project that involves retrieving Facebook news feed data using the graph API. Upon receiving the JSON object, I display it on the page. The "Likes" section is presented as an array of JSON objects like this: data.likes: { ...

I'm encountering difficulties in automatically populating the category field from an API

Hey there! I have set up a signup form and I am trying to automatically fetch categories from the server API to populate an input area. Everything seems to be in place, but for some reason, I am unable to retrieve the data. API: Here is the code I'm ...

Click on an Object within a modal window using JavaScript in Internet Explorer 8

I'm facing a strange issue with the SELECT object in a Modal Window. Within my HTML code, I have a button that opens a modal window when clicked. Inside this modal window, a JSP page is loaded. On this JSP page, there is a dropdown list created using ...

Utilize range slider to refine dataset

I have implemented a jquery datatable along with the range.slider plugin. My goal is to apply the range slider to filter out data in the last column. In my attempt, I am using search.push to accomplish this filtering process. Below is an example of my i ...

I'm struggling with developing react applications due to problems with canvas elements

I am currently using an M1 MacBook Pro, with Node version 15.4.1 and npm version 7.0.15. When I ran the command npx create-react-app my-app, it gave me this output: https://i.sstatic.net/OKKnA.jpg I have attempted various solutions but keep encountering ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

Understanding how to monitor a Boolean value that fluctuates in real-time within a three.js

Currently, I am working on developing a 3D 4x4x4 tic tac toe game using three.js. In order to determine the win condition for combinations, I have created a boolean array. With a total of 64 blocks (16*4), I have initialized a boolean array of size 64 with ...