Skip to content

Instantly share code, notes, and snippets.

@danielkcz
Last active July 26, 2023 21:51
Show Gist options
  • Save danielkcz/a4216782b5d4fee79a22eb09b457625f to your computer and use it in GitHub Desktop.
Save danielkcz/a4216782b5d4fee79a22eb09b457625f to your computer and use it in GitHub Desktop.
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
Copy link

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

@danielkcz
Copy link
Author

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
Copy link

@FredyC awesome! will check it out.

@gravitymedianet
Copy link

I am trying to find a solution with nested properties. Know of any?

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