Home > Blockchain >  Clean way to fill multiple inputs with puppeteer
Clean way to fill multiple inputs with puppeteer

Time:10-13

When using puppeteer I use page.type() and I've noticed that when working with more than one input field the code begins to repeat itself.

Here is the shortened version of what I'm doing:

        await page.type('#idFirstName', user.first_name);
        await page.type('#idEmailAddress', user.email);
        await page.type('#idLastName', user.last_name);
        await page.type('#idCity', user.city);

Is there any way to fill multiple input fields without repeating the await page.type()?

CodePudding user response:

Whenever you find yourself repeating the same syntax, it's usually an indicator that you can use a loop.

In your example code, you repeatedly invoke the Page.type method, whose signature looks like this:

class Page {
  type(
    selector: string,
    text: string,
    options?: { delay: number }
  ): Promise<void>;
}

You appear to be supplying arguments for the first two parameters (selector and text), so you can create an array of tuples which represent those arguments, and then use a for...of loop to iterate over that array, supplying the arguments each time:

const argumentsList = [
  ['#idFirstName', user.first_name],
  ['#idEmailAddress', user.email],
  ['#idLastName', user.last_name],
  ['#idCity', user.city],
];

for (const [selector, text] of argumentsList) {
  await page.type(selector, text);
}

You can also spread the arguments when invoking the function instead of destructuring them:

for (const args of argumentsList) await page.type(...args);
  • Related