prompts icon indicating copy to clipboard operation
prompts copied to clipboard

[Question]: How do I check if the prompt is cancelled when it is cancelled after the first prompt?

Open DomiDenie opened this issue 5 years ago • 2 comments

When the prompt is cancelled during the first question the response object is empty, but when it is cancelled later in the chain of prompts. The answers that are collected till that point are returned. Is there a way to blank this out onCancel?

DomiDenie avatar Oct 10 '19 14:10 DomiDenie

The only avalible callback at the moment is https://github.com/terkelg/prompts#optionsoncancel. Maybe you can get creative with the onState change callback https://github.com/terkelg/prompts#onstate

terkelg avatar Oct 18 '19 20:10 terkelg

Is there a way to blank this out onCancel?

@DomiDenie Yes. There are a couple of ways to do that using onCancel callback.

  • Adding custom attribute to the answers object (I prefer this option)
  • Deleting existing answers from the answers object.
// custom attribute
const prompts = require('prompts');

(async () => {
  const questions = [{ ... }];
  const onCancel = (prompt, answers) => {
    answers.__cancelled__ = true;
    return false;
  }

  const response = await prompts(questions, { onCancel });

  if (response.__cancelled__) {
    // handle cancellation
    return;
  }

  // process the response
})();
// delete existing answers
const prompts = require('prompts');

(async () => {
  const questions = [{ ... }];
  const onCancel = (prompt, answers) => {
    Object.keys(answers).forEach(answer => delete answers[answer]);

    return false;
  }

  const response = await prompts(questions, { onCancel });

  if (!Object.keys(response).length) {
    // handle cancellation
    return;
  }

  // process the response
})();

m-sureshraj avatar Nov 18 '19 02:11 m-sureshraj