| 1 |
import { createContext, Dispatch, SetStateAction, useContext, useState } from 'react'; |
| 2 |
|
| 3 |
export interface FormContextProps { |
| 4 |
/** Record of values for all fieldIds */ |
| 5 |
values: Record<string, string>; |
| 6 |
/** Record of errors for all fieldIds */ |
| 7 |
errors: Record<string, string>; |
| 8 |
/** Record of touched state for all fieldIds */ |
| 9 |
touched: Record<string, boolean>; |
| 10 |
/** Flag to determine the overall validity. True if the record of errors is empty. */ |
| 11 |
isValid: boolean; |
| 12 |
|
| 13 |
/** Get the value for a given fieldId */ |
| 14 |
getValue(fieldId: string): string; |
| 15 |
/** Set the value for a given fieldId */ |
| 16 |
setValue(fieldId: string, value: string): void; |
| 17 |
/** Set multiple values within the managed record of values */ |
| 18 |
setValues: Dispatch<SetStateAction<Record<string, string>>>; |
| 19 |
|
| 20 |
/** Get the error message for a given fieldId */ |
| 21 |
getError(fieldId: string): string; |
| 22 |
/** Set the error message for a given fieldId */ |
| 23 |
setError(fieldId: string, error: string | undefined): void; |
| 24 |
/** Set multiple errors within the managed record of errors */ |
| 25 |
setErrors: Dispatch<SetStateAction<Record<string, string>>>; |
| 26 |
|
| 27 |
/** Used to determine touched state for a given fieldId */ |
| 28 |
isTouched(fieldId: string): boolean; |
| 29 |
/** Used to update the touched state for a given fieldId */ |
| 30 |
setTouched(fieldId: string, isTouched: boolean): void; |
| 31 |
|
| 32 |
/** Triggers all fieldId-specific validators */ |
| 33 |
validate(): Record<string, string | null>; |
| 34 |
/** Set a validator for a specific fieldId */ |
| 35 |
setValidator(fieldId: string, validate: (value: string) => string | null): void; |
| 36 |
} |
| 37 |
|
| 38 |
const FormContext = createContext({} as FormContextProps); |
| 39 |
|
| 40 |
export const FormContextConsumer = FormContext.Consumer; |
| 41 |
|
| 42 |
export interface FormContextProviderProps { |
| 43 |
/** Record of initial values */ |
| 44 |
initialValues?: Record<string, string>; |
| 45 |
/** Any react node. Can optionally use render function to return context props. */ |
| 46 |
children?: React.ReactNode | ((props: FormContextProps) => React.ReactNode); |
| 47 |
} |
| 48 |
|
| 49 |
export const FormContextProvider: React.FC<FormContextProviderProps> = ({ initialValues, children }) => { |
| 50 |
const [values, setValues] = useState<Record<string, string>>(initialValues || {}); |
| 51 |
const [errors, setErrors] = useState<Record<string, string>>({}); |
| 52 |
const [validators, setValidators] = useState<Record<string, Function>>({}); |
| 53 |
const [touched, setTouched] = useState<Record<string, boolean>>({}); |
| 54 |
const isValid = Object.keys(errors)?.length === 0; |
| 55 |
|
| 56 |
const getValue = (fieldId: string) => |
| 57 |
Object.entries(values).reduce((acc, [id, value]) => (id === fieldId ? value : acc), ''); |
| 58 |
|
| 59 |
const setValue = (fieldId: string, value: string, triggerValidation: boolean = true) => { |
| 60 |
if (values[fieldId] !== value) { |
| 61 |
setValues((prevValues) => ({ ...prevValues, [fieldId]: value })); |
| 62 |
triggerValidation && validators[fieldId]?.(value); |
| 63 |
} |
| 64 |
}; |
| 65 |
|
| 66 |
const getError = (fieldId: string) => |
| 67 |
Object.entries(errors).reduce((acc, [id, error]) => (id === fieldId ? error : acc), ''); |
| 68 |
|
| 69 |
const setError = (fieldId: string, error: string) => |
| 70 |
errors[fieldId] !== error && |
| 71 |
setErrors(({ [fieldId]: _, ...prevErrors }) => ({ |
| 72 |
...prevErrors, |
| 73 |
...(!!error && { [fieldId]: error }) |
| 74 |
})); |
| 75 |
|
| 76 |
const isTouched = (fieldId: string) => |
| 77 |
Object.entries(touched).reduce((acc, [id, isTouched]) => (id === fieldId ? isTouched : acc), false); |
| 78 |
|
| 79 |
const setFieldTouched = (fieldId: string, isTouched: boolean) => |
| 80 |
touched[fieldId] !== isTouched && |
| 81 |
setTouched(({ [fieldId]: _, ...prevTouched }) => ({ |
| 82 |
...prevTouched, |
| 83 |
...(isTouched && { [fieldId]: isTouched }) |
| 84 |
})); |
| 85 |
|
| 86 |
const setValidator = (fieldId: string, validate: (value: string) => string | null) => |
| 87 |
validators[fieldId] !== validate && setValidators((prevValidators) => ({ ...prevValidators, [fieldId]: validate })); |
| 88 |
|
| 89 |
// Accumulate and return errors from all fields with validators. |
| 90 |
const validate = () => |
| 91 |
Object.entries(validators)?.reduce((acc: Record<string, string>, [id, validateField]) => { |
| 92 |
const fieldError = validateField(values[id]); |
| 93 |
|
| 94 |
if (fieldError) { |
| 95 |
acc[id] = fieldError; |
| 96 |
} |
| 97 |
|
| 98 |
return acc; |
| 99 |
}, {}); |
| 100 |
|
| 101 |
return ( |
| 102 |
<FormContext.Provider |
| 103 |
value={{ |
| 104 |
values, |
| 105 |
errors, |
| 106 |
touched, |
| 107 |
isValid, |
| 108 |
setValues, |
| 109 |
setErrors, |
| 110 |
getValue, |
| 111 |
setValue, |
| 112 |
getError, |
| 113 |
setError, |
| 114 |
validate, |
| 115 |
setValidator, |
| 116 |
isTouched, |
| 117 |
setTouched: setFieldTouched |
| 118 |
}} |
| 119 |
> |
| 120 |
{typeof children === 'function' ? ( |
| 121 |
<FormContext.Consumer>{(formContext) => children(formContext)}</FormContext.Consumer> |
| 122 |
) : ( |
| 123 |
children |
| 124 |
)} |
| 125 |
</FormContext.Provider> |
| 126 |
); |
| 127 |
}; |
| 128 |
FormContextProvider.displayName = 'FormContextProvider'; |
| 129 |
|
| 130 |
export const useFormContext = () => useContext(FormContext); |