Skip to content

Commit ecdb09d

Browse files
authored
Fix reset of unmounted inputs (#114)
1 parent 6adecf3 commit ecdb09d

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
dev
12
dist
23
node_modules
34
.DS_Store

src/useState.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,16 @@ export function useState({ initialState, onClear, onReset }) {
2323
setError({ [name]: inputError });
2424
}
2525

26-
const clearField = name => setField(name);
27-
const resetField = name => setField(name, initialValues.get(name));
26+
const clearField = name => {
27+
setField(name);
28+
};
29+
30+
const resetField = name => {
31+
setField(
32+
name,
33+
initialValues.has(name) ? initialValues.get(name) : initialState[name],
34+
);
35+
};
2836

2937
return {
3038
/**

test/useFormState-manual-updates.test.js

+21
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,27 @@ describe('useFormState manual updates', () => {
9595
expect(onReset).toHaveBeenCalled();
9696
});
9797

98+
it('resets an un-mounted for field', () => {
99+
const initialState = {
100+
first: 'bruce',
101+
last: 'wayne',
102+
};
103+
104+
const { root, formState, change } = renderWithFormState(
105+
([, input]) => <input {...input.text('first')} />,
106+
initialState,
107+
);
108+
109+
change({ value: '' }, root);
110+
expect(formState.current.values).toEqual({
111+
first: '',
112+
last: 'wayne',
113+
});
114+
115+
formState.current.reset();
116+
expect(formState.current.values).toEqual(initialState);
117+
});
118+
98119
it('sets the value of an input programmatically using from.setField', () => {
99120
const { formState } = renderWithFormState(([, input]) => (
100121
<input {...input.text('name')} />

0 commit comments

Comments
 (0)