Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Formik with MobX
function useFormik(props) {
// useState to keep the same observable around without recreating it on each render
const [formik] = React.useState(() =>
mobx.observable({
values: props.initialValues || {},
touched: {}
})
)
// just mutate state, this function itself can be considered an action+reducer
const handleChange = fieldName => event => {
formik.values[fieldName] = event.target.value;
};
const handleBlur = fieldName => event => {
formik.touched[fieldName] = true;
};
// props will be spread over the form inputs minimizing code necessary to setup such input
const getFieldProps = fieldName => ({
value: formik.values[fieldName],
onChange: handleChange(fieldName),
onBlur: handleBlur(fieldName)
});
return { handleChange, handleBlur, getFieldProps, ...formik };
}
function NameForm() {
// use the formik hook with optional initial values
const formik = useFormik({
initialValues: {
name: "",
email: ""
}
});
const { getFieldProps } = formik;
// notice the useObserver hook that takes care of re-rendering
return useObserver(() => (
<form>
<label>
Name:
<input type="text" {...getFieldProps("name")} />
</label>
<label>
Email:
<input type="text" {...getFieldProps("email")} />
</label>
<Debug formik={formik} />
<button type="submit">Submit</button>
</form>
));
}
@gastonmorixe

This comment has been minimized.

Copy link

@gastonmorixe gastonmorixe commented Jan 8, 2020

This is great, I have started a package using a similar Formik API with MobX because I needed it for a project with derived / calculated props requirements, feel free to check it out https://github.com/gastonmorixe/formik-mobx

@FredyC

This comment has been minimized.

Copy link
Owner Author

@FredyC FredyC commented Jan 8, 2020

Yea, I already have cooked up some more solid implementation of this used in production.

https://www.npmjs.com/package/@speedlo/xform

It's not exactly open-sourced yet. I want to get to it eventually. Polish of docs is definitely lacking, but perhaps it will inspire you in some way.

@gastonmorixe

This comment has been minimized.

Copy link

@gastonmorixe gastonmorixe commented Jan 10, 2020

@FredyC awesome! will check it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment