Search code examples
generatoryeomanprompt

Yeoman repeat prompt based on user input


For example, I want to ask the user for the type of bread:

        {
            type: 'list',
            name: 'breadType',
            message: `What type of bread do you want?`,
            choices: response => {
                const breadOptions = [
                    {
                        value: 'wheat',
                        name: 'Wheat Bread'
                    },
                    {
                        value: 'white',
                        name: 'White Bread'
                    }
                ];
                return breadOptions;
            },
            default: 0
        }

Then I'll ask for toppings based on the number of toppings they want:

    {
        when: response => response.breadType,
        type: 'input',
        name: 'numberOfToppings',
        message: 'Please enter how many toppings you want: '
    }

How would I prompt however many times user input for number of toppings?:

 {
        when: response => response.numberOfToppings,
        type: 'input',
        name: 'toppingChoices',
        message: 'Please provide your topping(s): '
 }

SAMPLE INPUT:

? Please enter how many toppings you want: 4
? Please provide your topping(s):cheese
? Please provide your topping(s):onions
? Please provide your topping(s):pickles
? Please provide your topping(s):tomatoes

I'm unfamiliar with yeoman syntax, please help.


Solution

  • I made a simple generator that solve your problem:

    const Generator = require('yeoman-generator');
    let toppings = [];
    
    module.exports = class extends Generator {
        async prompting() {
            const answers = await this.prompt([
                {
                    type: 'input',
                    name: 'numberOfToppings',
                    message: 'Please enter how many toppings you want: ',
                }
            ]);
    
            var length = answers.numberOfToppings;
            for(var i = 0; i < length; i++) {
                const answers2 = await this.prompt([
                    {
                        type: 'input',
                        name: 'toppings',
                        message: 'Please provide your topping(s):',
                    }
                ]);
                toppings.push(answers2.toppings);
            }
            console.log('Array: ' + toppings);
        }
    };