What is the best way to send a variable to an arrow function?

Is there a way to use the selector parameter inside an arrow function for an if statement without receiving an error stating that the selector is not defined?

static async valuesToArray(selector: string): Promise<void> {
    const data: (string | Date)[] = await page.$$eval(selector, cells =>
      cells.map(cell => {
        if (selector === contractsPo.contractDateCol) {
          return new Date(
            cell.textContent!.replace(/(\d{2}).(\d{2}).(\d{4})/, '$2/$1/$3'),
          );
        } else {
          return cell.textContent!;
        }
      }),
    );
  }
page.$$eval
([aria-colindex="2"])
— 59ms
Evaluation failed: ReferenceError: selector is not defined
    at eval (eval at evaluate (:303:29), <anonymous>:2:13)
    at Array.map (<anonymous>)
    at eval (eval at evaluate (:303:29), <anonymous>:1:16)
    at UtilityScript.evaluate (<anonymous>:305:22)
    at UtilityScript.<anonymous> (<anonymous>:1:44)

Answer №1

Make sure to pass the variable into the function as shown below:

static async valuesToArray(selector: string): Promise<void> {
    const data: (string | Date)[] = await page.$$eval((selector, cells) => {
        cells.map(cell => {
            if (selector === contractsPo.contractDateCol) {
                return new Date(
                cell.textContent!.replace(/(\d{2}).(\d{2}).(\d{4})/, '$2/$1/$3'),
                );
            } else {
                return cell.textContent!;
            }
        }),
    }, selector, cells); // Remember to pass in the selector here.
}

I usually use page.evaluate and then use document.querySelectorAll inside the function like this:

await page.evaluate((selector, cells) => {
    // Your code here

}, selector, cells); // Don't forget to pass in the selector here.

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

Creating an array of objects by parsing JSON using the jQuery .each() method

I am attempting to generate an array of objects by parsing a JSON file. Here is the pertinent code: //president object constructor function president(a_presName, a_presDates, a_presNick, a_presImage) { this.presName=a_presName; this.presDates=a_pr ...

Adjusting the StrokeWidth in pixels/em units on fabricjs

When adding a rectangle or circle to the canvas and adjusting the strokeWidth using a range input, how can we determine the value of strokeWidth in pixels, em, or percent? For instance, if we set strokeWidth to 5 within a range of 1-10, how much does the a ...

Accessing objects from a loop in JavaScript

In an effort to adhere to the principle of avoiding "polluting the global namespace" and due to the consensus that global variables are typically discouraged, I made a modification in my code by replacing global variables: stBgAsset15_src = $image.at ...

What is the process for utilizing GruntFile.coffee and package.json to extract or create the Lungo.js example files?

I want to experiment with the Lungo.js examples found here: https://github.com/tapquo/Lungo.js. However, when I try to run the index.html in the example directory, it seems like the components and package directories are empty. Although these directories d ...

Inline checkbox label with Bootstrap 5 styling

How can I align the checkbox with its label? Example <div class="row g-1 border-bottom p-3"> <div class="col border-end justify-content-center d-flex align-items-center"> <div class="h6 text-sm-center h-25&quo ...

Accessing a local JSON data file via an AJAX call

function fetchColor() { var promise = $.Deferred(); $.ajax ({ url: 'ajax/color/Red.json', dataType: 'json', type: 'get', success: function(data){ promise.resolve(data); ...

Is it possible to populate a div using jQuery Datatable?

Seeking help with jQuery datatable as a newbie. How can I populate divs instead of tables with the data from an ajax call? The structure should resemble a table: <div id="wrap"> <div class="drow"> <div class="dco ...

Using Vaadin: update Label text with TextField input after Button is clicked

I'm working on a simple Vaadin form where I want the text entered in a TextField to appear in a Label after the user clicks on a Button. Here's the code snippet: package com.example; import javax.servlet.annotation.WebServlet; import com.vaad ...

Tips for moving and filling data in a different component using NextJS

Currently, I am developing an application using Next.js and tailwindcss. The Issue In essence, I have a table consisting of 4 columns where each row contains data in 3 columns and the last column includes an "Update" button. The data in each row is genera ...

Setting a default value within an input tag: A step-by-step guide

const [userData, setUserData] = useState([]); const handleUserInfo = (id) => { fetch(`https://602e7c2c4410730017c50b9d.mockapi.io/users/${id}`) .then(res => res.json()) .then(data => setUserData(data)) } <inpu ...

The disappearance of UI elements in Angular 13 and Bootstrap 5 when new routes are introduced

After spending a considerable amount of time on website development, I have hit a roadblock with the navigation. Whenever I set up a route, the entire user interface disappears and refuses to load. I have searched extensively but found no solution to this ...

Establishing a PHP session variable and then initiating a redirect to a new page through the HREF method

I am working on a table that pulls IDs from a MySQL table named auctiontable and displays them in rows. Currently, I can easily append ?aid="1"or ?aid="2" to the end of the href attribute to utilize $_GET. However, I want to prevent users from controllin ...

Error: Attempted to search for 'height' using the 'in' operator in an undefined variable

I came across the following code snippet: $('.p1').click(function(){ var num = 10; var count = 0; var intv = setInterval(anim,800); function anim(){ count++; num--; ...

Utilizing AngularJS Directives to Transclude and efficiently organize data chunks

I'm facing a challenge as I try to convert a jQuery plugin I developed into an AngularJS directive. The issue lies in the transclusion aspect of the process. Link to jQuery Widget plugin: http://plnkr.co/edit/xxZIb2DyAere7pBY6qm7?p=preview Link to A ...

What is the best way to set up CORS in IE11 using C# with JQuery.ajax?

Having some trouble with CORS functionality in IE11. I need to perform ajax requests using jquery (or whatever the browser supports natively), without any additional libraries. These requests are cross-domain and function perfectly in Chrome and Firefox. ...

Click event inside a repeat loop

Working with AngularJS, I have a collection of colors that each have a specific title and type. These colors are displayed in a list format on the webpage. Now, I am looking to enhance this by incorporating a menu option that allows users to filter and vi ...

initiate a POST request using fetch(), where the data sent becomes the key of

Encountered an issue with sending a POST fetch request where the JSON String turns into the Object Key on the receiving end, specifically when using the { "Content-Type": "application/x-www-form-urlencoded" } header. I attempted to use CircularJSON to res ...

Jasmine is having trouble scrolling the window using executeScript

I usually use the following command: browser.driver.executeScript('window.scrollTo(0,1600);'); However, this command is no longer working. No errors are showing in the console, making it difficult to troubleshoot. Interestingly, the same scri ...

I'm perplexed by setting up Node.js in order to work with Angular.js

Currently following the Angular tutorial provided at https://docs.angularjs.org/tutorial, but I'm encountering confusion with the Node.js installation. Having already installed node globally on my Mac, the tutorial mentions: The tutorial instructio ...

Issue with Asp.Net MandatoryFieldValidator and JavaScript What You See Is What You Get Editor

Currently, I am utilizing the Javascript WYSIWYG tool from OpenWebWare along with Asp.Net's RequiredFieldValidator on a TextBox that is linked to the WYSIWYG. So far, everything is functioning properly, however, upon the first form submission attempt, ...