diff --git a/src/ui/interfaces/index.ts b/src/ui/interfaces/index.ts index 08a8458..5bfcf5e 100755 --- a/src/ui/interfaces/index.ts +++ b/src/ui/interfaces/index.ts @@ -110,17 +110,27 @@ export type FieldDefinition = { validator?: FieldValidator; } +type FormRef = ReturnType & { + toggleAlert(message?: string | null, options?: Partial): void +} export interface IWidgetSettings { apiUrl: string; locale: ILocaleSettings; mode?: string modeOptions: Partial, + form: FormRef + ) => Promise | void, + postAction?: ( + values: any, + fields: Record, + form: FormRef) => Promise | void, responseErrorHandler?: ( err: Error, - form: ReturnType & { - toggleAlert(message?: string | null, options?: Partial): void - }, + form: FormRef, fields: AdditionalFields ) => void }>>, diff --git a/src/ui/utils/form_generics.ts b/src/ui/utils/form_generics.ts index 47398a7..550bc27 100755 --- a/src/ui/utils/form_generics.ts +++ b/src/ui/utils/form_generics.ts @@ -153,7 +153,9 @@ export function useGenericForm( }, {}) try { + await settings.modeOptions?.[name]?.preAction?.(fieldsWithValues, mergedFields, formRef) await action?.(fieldsWithValues, mergedFields) + await settings.modeOptions?.[name]?.postAction?.(fieldsWithValues, mergedFields, formRef) } catch (e) { formErrorHandler(e) } finally { diff --git a/stories/CustomFields/01-Documentation.mdx b/stories/CustomFields/01-Documentation.mdx index 77cb606..d68aa78 100644 --- a/stories/CustomFields/01-Documentation.mdx +++ b/stories/CustomFields/01-Documentation.mdx @@ -32,6 +32,49 @@ CheckBox with `type: 'checkbox'` Code with `type: 'code'` Every other property or `type: 'text'` renders a TextField +## Action Helpers +You can execute your own defined functions for error handling and responses. + +To execute a function before or after the action successfully completed, define them with `preAction` or `postAction` property. +Example: +```js +new PlusAuthWidget('#widget', { + modeOptions: { + 'resetPassword': { + preAction(values, fields, formRef){ + // Executed just before http request is sent + if(values.password.includes('something')){ + // will be handled by responseErrorHandler + throw { error: 'my_custom_error' } + } + }, + postAction(){ + // Executed when action completed successfully + window.location.replace('https://myapplication.url/after-reset-password') + } + } + } +}) +``` + +Another common use case is handling form errors. For such cases you can define a function as `responseErrorHandler` and take action accordingly. + +For example: + +```js +new PlusAuthWidget('#widget', { + modeOptions: { + 'resetPassword': { + responseErrorHandler(error, formRef, fields){ + if(error && error.error === 'my_custom_error' ){ + formRef.toggleAlert('My custom text') + } + } + } + } +}) +``` + ## Field Properties