Encountered "Function undefined error when invoking within a map in TypeScript"

In my function, there is a map that looks like this:

mainFunc(){
// other logics

    data.map(function (item) {
      item.number = Math.round(item.number);
      item.total = item.last - item.first;
      item.quantity= item?.quantity ? quantityRange(item?.quantity): '';
    }); 

// other logics
}


quantityRange(quantity){
if(quantity){
   if(quantity < 100) return "Less Quantity";
   if(quantity < 500) return "Average Quantity";
   else return "Good Quantity"
   }
}

I placed the quantityRange() outside the mainFunc() and then called it within the ternary operator inside the map. However, upon running the code, I encountered an error: quantityRange() is not defined. Does this mean we cannot use functions in this way inside the map function in TypeScript?

I would greatly appreciate any assistance with this issue.

Answer №1

executeMainFunction(){
// additional operations
    const current = this; // ensure the context remains intact
    data.map(function (element) {
      element.number = Math.round(element.number);
      element.total = element.last - element.first;
      element.quantity= element?.quantity ? current.calculateQuantityRange(element?.quantity): '';
    }); 

// additional operations
}

When using the method with 'this' keyword, remember to bind it properly. There are various approaches to binding, such as storing it in a variable.

Answer №2

The reason for the error is because you forgot to define it properly. You must use the keyword function to create both of your functions. Additionally, there should not be a space between data.map(function (item); the parentheses must stick together. There were other syntax mistakes as well, but most of them have been corrected in the revised code.
The correct format should look like this:

function mainFunc() {
// additional logic

    data.map(function(item) {
        item.number = Math.round(item.number);
        item.total = item.last - item.first;
        item.quantity = item?.quantity ? quantityRange(item?.quantity): ''; // Issue lies with this line.
    }); 

// additional logic
};


function quantityRange(quantity) {
    if (quantity) {
        if (quantity < 100) {
            return "Less Quantity";
        }
        else if (quantity < 500) {
            return "Average Quantity";
        }
        else {
            return "Good Quantity";
        };
    };
};

I couldn't quite understand the purpose of line 6, but that seems to be where the mistake occurred. Could you clarify what you are trying to accomplish with that line so I can assist in correcting its syntax?

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

Save property using the useState hook

I am working on implementing a sorting function in the child component, where the props are passed in from the parent through an axios call. Should I: Store the prop in the child component's useState? Pass the parent's setState function as a pro ...

Experimenting with async generator using Jest

It has become clear that I am struggling with the functionality of this code, especially when it comes to testing with Jest. Despite my efforts to use an await...of loop, I am not getting any output. The file path provided to the generator is correct and I ...

When the user clicks, the template data should be displayed on the current page

I need help with rendering data from a template on the same HTML page. I want to hide the data when the back button is clicked and show it when the view button is clicked. Here is my code: <h2>Saved Deals</h2> <p>This includes deals wh ...

Having trouble sending values via POST request in Node.js using Express

Currently, I am in the process of learning how to use Express (v4) with Node.js. My main goal right now is to create a basic REST API. This API specifically focuses on one endpoint: /orders. The main functionality I am trying to achieve is the ability to r ...

Tips for modifying the text color of a div that is being iterated through using ngFor

I am facing an issue with a div that is being looped using ngFor. What I want to achieve is when a user clicks on one of the divs in the loop, only that particular div should change its text color. If another div is clicked, it should change color while th ...

Switching the position of a Button in Semantic UI React: Moving it from the Left to the

I need assistance with adjusting the position of a Semantic UI React Button. By default, the button is displayed on the left side, but I would like it to be on the right side instead. Can someone please provide guidance on how I can move the Semantic butto ...

Material UI Grid's layout does not support placing a select element within a row

As a newcomer in the world of full stack development, I am delving into coding projects to enhance my understanding of frontend technologies like React JS and Material UI. My latest endeavor involves creating a page that displays posts from the backend in ...

Encountering the issue of receiving undefined values for both error and url during the utilization

I'm currently working on a file called createCheckoutSession.ts: import { db } from '../firebase/firebaseInit'; import { collection, addDoc, onSnapshot } from 'firebase/firestore'; import { User } from 'firebase/auth'; e ...

Pinia store encountering a Typescript Vue component issue: error message "The property 'testStore' does not exist on the 'CreateComponentPublicInstance' type."

Within my <script setup> block, I have imported my testStore. However, whenever I attempt to use this.testStore.name in my Vue file, Vetur displays the following error: Property 'testStore' does not exist on type 'CreateComponentPublic ...

Utilizing Parent Method in VueJS Component: A Step-by-Step Guide

I need to access methods of the parent component from within the current one, without using props. Below is the structure in HTML: <div id="el"> <user v-for="user in users" :item="user"></user> </div> And here is the Vue code ...

Can the values in all fields of a JSON be combined or subtracted with those of another object containing the same fields?

I am currently working with a Mongoose.js schema that is structured as follows: { "City": String, "Year": String, "Population": Number, "Blah": Number, "Nested": { "Something": Number, "More stuff": Number } } Is there an efficient w ...

React component failing to update after receiving response from server for a specific room using socket.io-client with Python backend

I've developed a server backend in Python with Flask-SocketIO that includes a room feature for private conversations. When a user joins a room, the server triggers a function to inform the frontend where to direct messages to a specific user: socketio ...

How can I ensure the Jquery datepicker functions correctly?

I've been attempting to create a jsp page with some Jquery functionalities. Unfortunately, despite my best efforts, I am unable to make it work. I have downloaded jquery1.7.1 and jquery-ui1.8.17 (non-mini), renamed them to jquery171.js and jquery-ui. ...

Error: The function is not defined on this.props during the handleCHange event

After going through numerous answers to similar questions on this topic, I believe that I am following all the necessary steps but for some reason, it is not working. Below is the specific section of code that is causing the error: import React from &apos ...

What is the process of integrating hegel.js with a React application created using create-react-app?

Have you heard of Hegel.js? It's a powerful type checker that I recently discovered. Surprisingly, there isn't much information online about using hegel.js with React. Check it out at ...

Showing the information obtained from an API request once the user submits the form without the need to reload the page

I am currently working on a form that will take search query requests from users upon submission and then display the results by making an API call. My goal is to show these results without the page having to refresh, using AJAX. The backend connection to ...

Updating the parent controller's scope from a directive in AngularJS does not reflect changes

HTML: <div ng-app="myApp" ng-controller="Controller"> <test ng-if="toggle" props="condition"></test> </div> Javascript: var myApp = angular.module('myApp', []); myApp.controller('Controller', ['$scop ...

Transforming the color of a globe from black to white with gio js

After searching for a solution to change the color of a Three.js globe, I came across a link that didn't work as expected: Change the color of a Three.js globe. My goal is to change the globe color from black to white using . I attempted to use the f ...

Unable to associate Slider values with TextFields in MaterialUI

Currently, I am trying to create a slide with 2 markers to indicate a price range and interact with it on the slide. Although I have linked the input with the slider, the connection from the slider to the input is not functioning properly. My attempt was t ...

Revealing the Webhook URL to Users

After creating a connector app for Microsoft Teams using the yo teams command with Yeoman Generator, I encountered an issue. Upon examining the code in src\client\msteamsConnector\MsteamsConnectorConfig.tsx, I noticed that the webhook URL w ...