Skip to content

Commit

Permalink
Fix getValue and setValue when a field has not been mounted
Browse files Browse the repository at this point in the history
  • Loading branch information
nikhilag committed Feb 8, 2023
1 parent 0593a8f commit 21a0e5c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 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-recoil-form",
"version": "0.3.2",
"version": "0.3.3",
"license": "MIT",
"author": "Wit By Bit",
"main": "dist/index.js",
Expand Down
28 changes: 26 additions & 2 deletions src/FormProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,9 @@ export function useFormContext() {
newValue: { value?: any; extraInfo?: any }
) => {
const get = snapshotToGet(snapshot);
const initialValues = get(
formInitialValuesAtom(formId)
) as InitialValues;
const newAtomData = {} as Partial<IFieldAtomValue>;
if (newValue.value !== undefined) {
newAtomData.data = newValue.value;
Expand All @@ -329,7 +332,14 @@ export function useFormContext() {
type: fieldKey.type,
formId,
}),
(atomValue) => Object.assign({}, atomValue, newAtomData)
(atomValue) => {
const updatedAtomData = Object.assign({}, atomValue, newAtomData);
// If field has not been mounted, this part will ensure that the setValue is not overridden by old initial values
if (initialValues.version > updatedAtomData.initVer) {
updatedAtomData.initVer = initialValues.version;
}
return updatedAtomData;
}
);
} else if (fieldKey.type === 'field-array') {
setFieldArrayDataAndExtraInfo(
Expand Down Expand Up @@ -364,7 +374,21 @@ export function useFormContext() {
formId,
})
) as IFieldAtomValue;
return { value: fieldAtom.data, extraInfo: fieldAtom.extraInfo };
const initialValuesAtom = get(
formInitialValuesAtom(formId)
) as InitialValues;
let value = fieldAtom.data;
let extraInfo = fieldAtom.extraInfo;
// Using initial value if field has not been mounted/initialized yet
if (
!key.ancestors?.length &&
value === undefined &&
fieldAtom.initVer < initialValuesAtom.version
) {
value = getPathInObj(initialValuesAtom.values, key.name);
extraInfo = getPathInObj(initialValuesAtom.extraInfos, key.name);
}
return { value, extraInfo };
} else if (key.type === 'field-array') {
const { data, extraInfo } = getFieldArrayDataAndExtraInfo(
formId,
Expand Down

0 comments on commit 21a0e5c

Please sign in to comment.