Great feedback from @luisherranz
Use generators for any asynchronous operation, instead of async/await (or promises).
*submitForm( event ) {
const context = getContext();
const { ref } = getElement();
event.preventDefault();
const formData = new FormData( ref );
formData.append( 'action', 'submit_feedback' );
formData.append( 'nonce', context.nonce );
formData.append( 'postId', context.postId );
context.isFormProcessing = true;
try {
const data = yield fetch( context.ajaxUrl, {
method: 'POST',
credentials: 'same-origin',
body: formData
}).then( r => r.text() )
context.hasSuccess = true;
context.formMessage = "Success!";
} catch( error ) {
console.error( 'Error:', error );
context.hasError = true;
context.formMessage = "Error!";
}
},
This is a requirement for the Interactivity API. In your case, everything works fine, but it could cause issues with the scope.
If you want to keep using promises instead, you need to wrap all the promise callbacks with a withScope(cb) function.
Great feedback from @luisherranz