Skip to content

Commit

Permalink
fix(setFormikInitialValue): do not override initial values passed fro…
Browse files Browse the repository at this point in the history
…m formik

Fixes #8
  • Loading branch information
Almouro committed May 10, 2018
1 parent 132e92b commit ff019be
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
27 changes: 20 additions & 7 deletions src/__tests__/setFormikInitialValue.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,22 @@ import { setFormikInitialValue } from "../..";

console.error = jest.fn();

const setFieldValue = jest.fn();
let setFieldValue;
let Input;

const withFormikMock = withContext({ formik: PropTypes.object }, () => ({
formik: {
setFieldValue
}
}));
const Input = compose(withFormikMock, setFormikInitialValue)(TextInput);
beforeEach(() => {
setFieldValue = jest.fn();

const withFormikMock = withContext({ formik: PropTypes.object }, () => ({
formik: {
setFieldValue,
values: {
"this input has been set by formik": "set value"
}
}
}));
Input = compose(withFormikMock, setFormikInitialValue)(TextInput);
});

describe("setFormikInitialValue", () => {
it("sets the initial value to ''", () => {
Expand All @@ -27,4 +35,9 @@ describe("setFormikInitialValue", () => {
const wrapper = mount(<Input name="inputName" someProp="someValue" />);
expect(wrapper.find(TextInput).props().someProp).toEqual("someValue");
});

it("does not set initial value if set by formik, e.g. with initial values", () => {
const wrapper = mount(<Input name="this input has been set by formik" />);
expect(setFieldValue).not.toBeCalled()
});
});
7 changes: 6 additions & 1 deletion src/setFormikInitialValue.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import React from "react";
import { compose, mapProps } from "recompose";
import { has } from "lodash";
import withFormik from "./withFormik";

const setFormikInitialValue = WrappedInput => {
return class WithFocusProp extends React.PureComponent {
constructor(props) {
super(props);
props.formik.setFieldValue(props.name, "");

const { formik, name } = props;
if (!has(formik.values, name)) {
formik.setFieldValue(name, "");
}
}

render() {
Expand Down

0 comments on commit ff019be

Please sign in to comment.