Skip to content

Commit ff019be

Browse files
committed
fix(setFormikInitialValue): do not override initial values passed from formik
Fixes #8
1 parent 132e92b commit ff019be

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

src/__tests__/setFormikInitialValue.js

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,22 @@ import { setFormikInitialValue } from "../..";
88

99
console.error = jest.fn();
1010

11-
const setFieldValue = jest.fn();
11+
let setFieldValue;
12+
let Input;
1213

13-
const withFormikMock = withContext({ formik: PropTypes.object }, () => ({
14-
formik: {
15-
setFieldValue
16-
}
17-
}));
18-
const Input = compose(withFormikMock, setFormikInitialValue)(TextInput);
14+
beforeEach(() => {
15+
setFieldValue = jest.fn();
16+
17+
const withFormikMock = withContext({ formik: PropTypes.object }, () => ({
18+
formik: {
19+
setFieldValue,
20+
values: {
21+
"this input has been set by formik": "set value"
22+
}
23+
}
24+
}));
25+
Input = compose(withFormikMock, setFormikInitialValue)(TextInput);
26+
});
1927

2028
describe("setFormikInitialValue", () => {
2129
it("sets the initial value to ''", () => {
@@ -27,4 +35,9 @@ describe("setFormikInitialValue", () => {
2735
const wrapper = mount(<Input name="inputName" someProp="someValue" />);
2836
expect(wrapper.find(TextInput).props().someProp).toEqual("someValue");
2937
});
38+
39+
it("does not set initial value if set by formik, e.g. with initial values", () => {
40+
const wrapper = mount(<Input name="this input has been set by formik" />);
41+
expect(setFieldValue).not.toBeCalled()
42+
});
3043
});

src/setFormikInitialValue.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
import React from "react";
22
import { compose, mapProps } from "recompose";
3+
import { has } from "lodash";
34
import withFormik from "./withFormik";
45

56
const setFormikInitialValue = WrappedInput => {
67
return class WithFocusProp extends React.PureComponent {
78
constructor(props) {
89
super(props);
9-
props.formik.setFieldValue(props.name, "");
10+
11+
const { formik, name } = props;
12+
if (!has(formik.values, name)) {
13+
formik.setFieldValue(name, "");
14+
}
1015
}
1116

1217
render() {

0 commit comments

Comments
 (0)