This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
website/hooks/useForm/useForm.ts

133 lines
3.8 KiB
TypeScript
Raw Normal View History

2021-10-26 16:38:55 +02:00
import { useMemo, useState } from 'react'
import useTranslation from 'next-translate/useTranslation'
import { Type } from '@sinclair/typebox'
import type { HandleForm } from 'react-component-form'
2021-10-26 16:38:55 +02:00
import type { ErrorObject } from 'ajv'
import { FetchState, useFetchState } from '../useFetchState'
import { ajv } from '../../tools/ajv'
2021-10-26 16:38:55 +02:00
import { getErrorTranslationKey } from './getErrorTranslationKey'
import { replaceEmptyStringInObjectToNull } from './replaceEmptyStringInObjectToNull'
import type { ObjectAny } from '../../tools/types'
import { handleCheckboxBoolean } from './handleCheckboxBoolean'
2021-10-26 16:38:55 +02:00
interface Errors {
[key: string]: ErrorObject<string, any> | null | undefined
}
const findError = (
field: string
): ((value: ErrorObject, index: number, object: ErrorObject[]) => boolean) => {
return (validationError) => validationError.instancePath === field
}
export type GetErrorTranslation = (error?: ErrorObject | null) => string | null
export interface UseFormOptions {
validateSchema: { [key: string]: any }
replaceEmptyStringToNull?: boolean
resetOnSuccess?: boolean
2021-10-26 16:38:55 +02:00
}
export type HandleSubmit = (callback: HandleSubmitCallback) => HandleForm
interface Message {
type: 'error' | 'success'
value: string
}
export type HandleSubmitCallback = (
formData: ObjectAny,
2021-10-26 16:38:55 +02:00
formElement: HTMLFormElement
) => Promise<Message | null>
export interface UseFormResult {
message: string | null
setMessageTranslationKey: React.Dispatch<
React.SetStateAction<string | undefined>
>
fetchState: FetchState
setFetchState: React.Dispatch<React.SetStateAction<FetchState>>
2021-10-26 16:38:55 +02:00
getErrorTranslation: GetErrorTranslation
handleSubmit: HandleSubmit
errors: Errors
}
export const useForm = (options: UseFormOptions): UseFormResult => {
const {
validateSchema,
replaceEmptyStringToNull = false,
resetOnSuccess = false
} = options
2021-10-26 16:38:55 +02:00
const { t } = useTranslation()
const [fetchState, setFetchState] = useFetchState()
2021-10-26 16:38:55 +02:00
const [messageTranslationKey, setMessageTranslationKey] = useState<
string | undefined
>(undefined)
const [errors, setErrors] = useState<Errors>({})
const validateSchemaObject = useMemo(() => {
return Type.Object(validateSchema)
}, [validateSchema])
2021-10-26 16:38:55 +02:00
const validate = useMemo(() => {
return ajv.compile(validateSchemaObject)
}, [validateSchemaObject])
2021-10-26 16:38:55 +02:00
const getErrorTranslation = (error?: ErrorObject | null): string | null => {
if (error != null) {
return t(getErrorTranslationKey(error)).replace(
'{expected}',
error?.params?.limit
)
}
return null
}
const handleSubmit: HandleSubmit = (callback) => {
return async (formData: ObjectAny, formElement) => {
if (replaceEmptyStringToNull) {
formData = replaceEmptyStringInObjectToNull(
formData,
validateSchemaObject.required
)
}
formData = handleCheckboxBoolean(formData, validateSchemaObject)
2021-10-26 16:38:55 +02:00
const isValid = validate(formData)
if (!isValid) {
setFetchState('error')
2021-10-26 16:38:55 +02:00
const errors: Errors = {}
for (const property in validateSchemaObject.properties) {
2021-10-26 16:38:55 +02:00
errors[property] = validate.errors?.find(findError(`/${property}`))
}
setErrors(errors)
} else {
setErrors({})
setFetchState('loading')
2021-10-26 16:38:55 +02:00
const message = await callback(formData, formElement)
if (message != null) {
setMessageTranslationKey(message.value)
if (message.type === 'success') {
setFetchState('success')
if (resetOnSuccess) {
formElement.reset()
}
2021-10-26 16:38:55 +02:00
} else {
setFetchState('error')
2021-10-26 16:38:55 +02:00
}
}
}
}
}
return {
getErrorTranslation,
errors,
fetchState,
setFetchState,
2021-10-26 16:38:55 +02:00
handleSubmit,
message: messageTranslationKey != null ? t(messageTranslationKey) : null,
setMessageTranslationKey
2021-10-26 16:38:55 +02:00
}
}