Skip to content

Commit

Permalink
fix: resolve falsy model initial value closes #4200
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Apr 14, 2023
1 parent 7a14186 commit 07418b9
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
27 changes: 25 additions & 2 deletions packages/vee-validate/src/useFieldState.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { computed, reactive, ref, Ref, unref, watch } from 'vue';
import { computed, isRef, reactive, ref, Ref, unref, watch } from 'vue';
import { FieldMeta, FieldState, MaybeRef, PrivateFormContext } from './types';
import { getFromPath, isEqual } from './utils';

Expand Down Expand Up @@ -113,7 +113,7 @@ export function _useFieldValue<TValue = unknown>(
// otherwise use the configured initial value if it exists.
// prioritize model value over form values
// #3429
const currentValue = modelValue ? unref(modelValue) : getFromPath(form.values, unref(path), unref(initialValue));
const currentValue = resolveModelValue(modelValue, form, initialValue, path);
form.stageInitialValue(unref(path), currentValue, true);
// otherwise use a computed setter that triggers the `setFieldValue`
const value = computed<TValue>({
Expand All @@ -132,6 +132,29 @@ export function _useFieldValue<TValue = unknown>(
};
}

/*
to set the initial value, first check if there is a current value, if there is then use it.
otherwise use the configured initial value if it exists.
prioritize model value over form values
#3429
*/
function resolveModelValue<TValue>(
modelValue: MaybeRef<TValue> | undefined,
form: PrivateFormContext,
initialValue: MaybeRef<TValue> | undefined,
path: MaybeRef<string>
): TValue {
if (isRef(modelValue)) {
return unref(modelValue);
}

if (modelValue !== undefined) {
return modelValue;
}

return getFromPath(form.values, unref(path), unref(initialValue)) as TValue;
}

/**
* Creates meta flags state and some associated effects with them
*/
Expand Down
23 changes: 23 additions & 0 deletions packages/vee-validate/tests/Form.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2546,6 +2546,29 @@ describe('<Form />', () => {
expect(input.value).toBe(value.value);
});

// #4200
test('Falsy model value should still have priority over form value', async () => {
const value = ref(0);
mountWithHoc({
setup() {
const initials = { age: 2 };
return {
value,
initials,
};
},
template: `
<VForm :initial-values="initials">
<Field name="age" type="number" v-model="value" />
</VForm>
`,
});

await flushPromises();
const input = document.querySelector('input') as HTMLInputElement;
expect(input.value).toBe('0');
});

test('handles invalid submissions', async () => {
const invalidSpy = vi.fn();
const validSpy = vi.fn();
Expand Down

0 comments on commit 07418b9

Please sign in to comment.