SweetAlert2 – Do not prompt in the future

NPM repository is great too, where we can find a lot of very good tools. On of them is SweetAlert2. Library to qucikly implement dialogs with errors, success messages or question. This library also allows to implement simple forms, like question about youir name with input, selection field, radio, files upload or other, custom template. This small tutorial is how to add “do not prompt in the future” to SweetAlert2 dialog. It’s vary simple, but some dev can be confused, how to add this, because it’s in conflict with some build-in options.

Sweet alert has build-in option to use several input types. One of them is checkbox, it’s what we need to allow user check to not prompt him in the future. The problem is, that we can use this type only one time. If we ask user about something, and he can decide: yes or now, result of SweetAlert2 promise is result of checkbox, not our question. It can be confusing, because we can check our question, but what about real user decision? There is solution – we should check not only result value, but also if there is dismiss property in result object. Using that construction, you can simply decide to prompt again in the future, or just skip this.

There is small example using that construction, also with saving user decision about prompt in local storage. It’s only example, in other case, you can save it in database using ajax, or make whole request with additional information, it’s your choice:

if (!localStorage.getItem('noAskUser')) {
	let result = await window.swal({
	    title: 'We will do something important',
	    text: 'We will do it. Are you sure?',
	    input: 'checkbox',
	    inputPlaceholder: 'Do not prompt me in the future',
	    type: 'question',
	    showCancelButton: true,
	    confirmButtonText: 'Yes',
	    cancelButtonText: 'No'
	})

	// Here we can handle no option
	if (result.dismiss) {
	    return
	}

	// Here we can save data from checkbox
	if (result.value) {
	    localStorage.setItem('noAskUser', '1')
	}
}

doSomethingImportant()

And it’s all. I know, that it’s a very simple tutorial, but maybe can help someone to implement this. What about sitaution, when you want to use for example selection or input with additional checbox? In that case, you must use custom html with your inputs and handle all data manually – of course you can still use dismiss prop from result, to escape when user decides to cancel.