Search code examples
reactjssweetalert2

Show error message from preConfirm in sweetalert2


Im using sweetalert2 and sweetalert2-react-content. My inputValidator works fine, it present errors to the user. How can I do the same in the preConfirm where I have an AJAX request?

    MySwal.fire({
        title: 'title',
        input: 'text',
        html: this.renderInfoText(),
        showLoaderOnConfirm: true,
        inputValidator: (value) => {
            return new Promise((resolve) => {
              if (this.validate(value)) { 
                resolve()
              } else {
                resolve('check formatting...')
              }
            })
        },            
        preConfirm: (pno) => {
            return axios.post('/some/route', { pno })
                .then(response => { 
                    // ...
                })
                .catch(error => {
                    // show an error message to the user from here?
                });
        }
    }) 

Solution

  • This is actually documented in the examples under the AJAX request example. Here is my solution:

    MySwal.fire({
        title: 'title',
        input: 'text',
        html: this.renderInfoText(),
        showLoaderOnConfirm: true,
        inputValidator: (value) => {
            return new Promise((resolve) => {
              if (this.validate(value)) { 
                resolve()
              } else {
                resolve('check formatting...')
              }
            })
        },            
        preConfirm: (pno) => {
            return axios.post('/some/route', { pno })
                .then(response => { 
                    // ...
                })
                .catch(error => {
                    if (error.response.status === 404) {
                        MySwal.showValidationMessage(error.response.data.message)                        
                    }                        
                });
        }
    })