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

4

14

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?

Mckinzie answered 27/3, 2018 at 18:51 Comment(3)
Hey did you get an answer for this?Lengthen
@ManishJangir see my answer, it provides 2 solutions.Cookbook
For the version 9.x, the answer is at github.com/SBoudrias/Inquirer.js#ask-a-question-conditionallyTronna
C
7

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;
  },
}
Cookbook answered 29/7, 2018 at 22:55 Comment(8)
I think the second option will result in an answers is not defined error.Isolation
No, this should contain the results of the given answers so far as the when is called afterwards and the first param are the given answers. You can call it however you want to. It is like deferred / .then() in jQuery. See github.com/SBoudrias/Inquirer.js/blob/master/packages/inquirer/…Cookbook
@DanielRuf I have given the second option a try but I do not seem to be able to access answers outside of the when function. I have also gone to the link and also to github.com/SBoudrias/Inquirer.js, and it seems that these examples are only using the when as a bool and not to pass the 'answers' value back to the prompt code eg. as answers.name in message above. I am not sure whether this is because the code/material has changed since your post. Would you be able to advise whether this is still possible?Oho
Generally it should work. The answers are all available in answers. The when is just a conditional to run the prompt in the case the return value is true.Cookbook
The first option returns Hershey [PLOP] No generator found in plopfile. The second one returns answers is not defined.Advent
Well, the API may have changed in inquirer 7. See npmjs.com/package/inquirer/v/6.5.1 for the docs for version 6. The question and answer were for inquirer 6.Cookbook
For v7 please check the examples at npmjs.com/package/inquirer/v/7.1.0#examplesCookbook
Hi @DanielRuf, this my setup currently. I am using async await but failed and moved to .then but still failed. Do you have any idea as to why and how to fix this?Advent
Q
6

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 }
Quamash answered 27/4, 2020 at 0:36 Comment(2)
Works great! Thank you. Borrowing from what you posted, I am posting my implementation below.Fideicommissary
If you look closely the question was / is about v6 ;-) Since 2018 there were several new releases. So for usre my answer does not work with v7 maybe but the answer from me could be updated to make this clear instead of creating multiple answers. At the time of asking, my answer was the correct one. =)Cookbook
B
4

I am a little bit late to the party, but came across this question while searching for a solution to do exactly this. To be complete, in version 7 it is possible to pass a function to the message property, that gets the answers like so:

inquirer
  .prompt([
    {
      type: "input",
      name: "name",
      message: "What is your name?",
    },
    {
      type: "list",
      name: "food",
      message: (answers) => `What would you like to eat ${answers.name}?`,
      choices: ["Hotdogs", "Pizza"],
    },
  ])
  .then((answers) =>
    console.log(`Enjoy your ${answers.food}, ${answers.name}!`)
  );
Basel answered 21/1, 2021 at 20:14 Comment(0)
F
0

const run = async () => {
  try {
    const ans1 = await inquirer.prompt([
      {},
    ]);

    const ans2 = await inquirer.prompt([
      {},
    ]);

    return { ...ans1, ...ans2 };

    inquirer.prompt([]);

  } catch (err) {
    if (err) {
      switch (err.status) {
        case 401:
          console.log('401');
          break;
        default:
          console.log(err);
      }
    }
  }
};

run();
Fideicommissary answered 16/9, 2020 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.