Jay
Jay

Reputation: 23

In node js, how do I create a prompt loop using inquirer?

For some reason, npm inquirer will blast through a while loop without prompting the user questions. The only way I can think of(cleanly) is to put it in function with a switch like the following:

function callMenu (selection){
  switch (selection){
    case 'main':
        //Use inquirer to show main menu and set selection = 'selection1' or selction = 'selection2'
        callMenu(selection);
        break;
    case 'selection1':
        //Use inquirer to show selection1 second level menu then go back to main menu
        callMenu('main');
        break;
    case 'selection2':
        //Use inquirer to show selection2 second level menu then go back to main menu
        callMenu('main');
        break;
   }
}
callMenu('main');

The problem is, I do not want to create a leak on call stack by calling the function within its self.

Upvotes: 1

Views: 3930

Answers (1)

cullanrocks
cullanrocks

Reputation: 497

You are definitely on the right track. I created inquirer submenus in different node modules so they can get called from any prompt menu. I also have my main menu as it's own module so it can be called from anywhere in any of the submenus.

So this is what my mainMenu.js file looks like:

const menu = () => {
  inquirer
    .prompt([{
      type: 'input',
      name: 'menu',
      message: "Type 'Menu' or hit enter to see the menu. Type in a player's name to search for a player."
    }]).then(answer => {
      answer.menu === '' ? subMenu.subMenu() :
        answer.menu.toLowerCase().trim() === 'menu' ? subMenu.subMenu() :
        tools.quickNameLookup(answer.menu);
    });
}

module.exports.menu = menu;

And here is what my subMenus.js file looks like:

const subMenu = () => {
  inquirer
    .prompt([{
      type: 'list',
      name: 'subMenu',
      message: 'Welcome to the MLB stats app. What would you like to do?',
      choices: ['Roster Search Menu', 'Player Search Menu', 'Player Statistics Menu', 'Leaderboards', 'Reports Menu', 'Back']
    }]).then(submenu => {
      let currentMenu = Object.keys(submenu)[0];
      switch (submenu.subMenu) {
        case 'Roster Search Menu':
          rosterMenu.rosterSearchPrompt(currentMenu);
          break;
        case 'Player Search Menu':
          playerSearchMenu.playerSearchPrompt(currentMenu);
          break;
        case 'Player Statistics Menu':
          statisticsMenu.statsSearchPrompt(currentMenu);
          break;
        case 'Reports Menu':
          reportsMenu.reportsPrompt(currentMenu);
          break;
        case 'Leaderboards':
          leaderboardsMenu.leaderboardsPrompt();
        case 'Back':
          menu.menu();
          break;
      }
    });
};

module.exports.subMenu = subMenu;

Works for input prompts but I prefer using lists when I can to avoid user error.

Upvotes: 2

Related Questions