How to pass variable to an arrow function?

Viewed 411

I want to use selector parameter inside arrow function for an if statement. But inside my if() statement I receive an error that says, that selector is not defined. Is there an any way I can fix this?

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)
1 Answers

You need to actually pass the variable into the function as well. Should look something like this instead:

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); // This is the important part of passing in the selector.
}

Typically I use page.evaluate like this and then use document.querySelectorAll inside the function but it shouldn't be any different:

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

}, selector, cells); // Again, be sure to actually pass in the selector here.

Related