Skip to content

Commit

Permalink
Merge pull request #6 from n0eyes/develop
Browse files Browse the repository at this point in the history
Release: v1.1.2
  • Loading branch information
n0eyes authored Dec 30, 2023
2 parents 8fa7c6a + 2e9e2ee commit fecd143
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-tiniest-form",
"version": "1.0.2",
"version": "1.1.2",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"browser": "./browser/specific/main.js",
Expand Down
24 changes: 16 additions & 8 deletions src/hooks/Form/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const useFormStore = <DefaultValues extends FormFields = FormFields>(
type FormErrors = Errors<DefaultValues>;
type Name = FieldName<DefaultValues>;

const formStore = useRef(createFormsStore<DefaultValues>(options?.defaultValues)).current;
const formStore = useRef(createFormsStore<DefaultValues>(options)).current;

const [snapshot, setSnapshot] = useState<FormStore>(formStore.store);

Expand Down Expand Up @@ -125,6 +125,10 @@ const useForm = <DefaultValues extends FormFields>(options?: UseFormOptions<Defa
onBlur?(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>): void;
},
) => {
const isControlledValue = options?.value !== undefined;

const controlledValue = parseToInputValue(options?.value);

const onChange = (e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const {
target: { value },
Expand All @@ -148,21 +152,25 @@ const useForm = <DefaultValues extends FormFields>(options?: UseFormOptions<Defa
const ref: RefCallback<HTMLInputElement | HTMLSelectElement> = instance => {
if (!instance) return;

/**@todo need? */
instance.value = getFieldValue(name);
if (!getFieldInfo(name)?.registered) {
const defaultValue = getFieldValue(name);

registerField(name, {
value: parseToInputValue(options?.value),
validations: options?.validations,
ref: instance,
});
registerField(name, {
value: controlledValue || defaultValue,
validations: options?.validations,
ref: instance,
});

instance.value = getFieldValue(name);
}
};

return {
name,
onChange,
onBlur,
ref,
...(isControlledValue ? { value: controlledValue } : {}),
};
};

Expand Down
2 changes: 1 addition & 1 deletion src/utils/formStore/createFormStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ const createFormsStore = <DefaultValues extends FormFields>(
store[name] = {
...store[name],
...options,
value: store[name]?.registered ? store[name]?.value : parseToInputValue(options?.value),
value: parseToInputValue(options?.value),
registered: true,
};
};
Expand Down

0 comments on commit fecd143

Please sign in to comment.