Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use previous answers in inquirer when presenting a prompt (inquirer v6)?

So what I want to do is use a previous answer when asking a question further down the line. Basically so that I can show a summary of what will be created and ask for a verification.

this.prompt([   
    {
      type: 'input',
      name: 'name',
      message: 'What is your name?'
      default: 'Jake'
    },
    {
      type: 'confirm',
      name: 'summary',
      message: 'Is this information correct? Your name is:' + answers.name',
    }

is there an easy way to achieve this? Or another way to achieve a summary type thing that lists out all previous answers?

like image 557
Ari Shaposhnik Avatar asked Mar 27 '18 18:03

Ari Shaposhnik


2 Answers

Either nest inquirer calls:

inquirer
  .prompt({
    type: 'list',
    name: 'chocolate',
    message: "What's your favorite chocolate?",
    choices: ['Mars', 'Oh Henry', 'Hershey']
  })
  .then(() => {
    inquirer.prompt({
      type: 'list',
      name: 'beverage',
      message: 'And your favorite beverage?',
      choices: ['Pepsi', 'Coke', '7up', 'Mountain Dew', 'Red Bull']
    });
  });

Or use the when function.

{
  type: 'confirm',
  name: 'summary',
  message: 'Is this information correct? Your name is:' + answers.name,
  when: function( answers ) {
    // Only run if user set a name
    return !!answers.name;
  },
}
like image 199
Daniel Ruf Avatar answered Oct 12 '22 23:10

Daniel Ruf


As far as I am concerned Daniel's answer does not work for inquirer 7. A workaround could be splitting the big prompt into several, and wrapping them using an anonymous async function. This will always be safe.

const inquirer = require("inquirer");

(async () => {
  const ans1 = await inquirer.prompt([
    {
      type: "input",
      name: "name",
      message: "What is your name?",
      default: "Jake",
    },
  ]);
  const ans2 = await inquirer.prompt([
    {
      type: "confirm",
      name: "summary",
      message: "Is this information correct? Your name is:" + ans1.name,
    },
  ]);
  return { ...ans1, ...ans2 };
})()
  .then(console.log)
  .catch(console.error);

This will log:

{ name: 'Foo bar', summary: true }
like image 39
Tianyi Shi Avatar answered Oct 12 '22 23:10

Tianyi Shi