Reputation: 141
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?
Upvotes: 14
Views: 12782
Reputation: 179
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}!`)
);
Upvotes: 4
Reputation: 868
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();
Upvotes: 0
Reputation: 969
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 }
Upvotes: 6
Reputation:
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;
},
}
Upvotes: 7