Skip to content

Instantly share code, notes, and snippets.

@gianmarcotoso
Last active February 19, 2019 10:02
Show Gist options
  • Save gianmarcotoso/80db17580460f7dcfc8008b8d4c9eee3 to your computer and use it in GitHub Desktop.
Save gianmarcotoso/80db17580460f7dcfc8008b8d4c9eee3 to your computer and use it in GitHub Desktop.
A `useForm` hook to handle forms within a React component using the hooks API
import { useState } from 'react'
export const useForm = (initialValue, middlewareFn) => {
const [data, setData] = useState(initialValue);
const middleware =
typeof middlewareFn === "function" ? middlewareFn : data => data;
/*
- onChange(event)
uses the event target's `name` and `value` (or `checked` if the type of the target is "checkbox")
to update the state's corresponding value
- onChange(delta, shouldReplaceState)
merges `delta` with the state or, if `shouldReplaceState` is true, replaces the state with
delta altogether
- onChange(name, value)
sets the key with the name contained in `name` on the state to `value`
*/
const onChange = (...args) => {
if (args.length === 0) {
return data;
}
const [maybeEvent] = args;
if (maybeEvent.nativeEvent && maybeEvent.nativeEvent instanceof Event) {
const [event] = args;
const update = middleware({
...data,
[event.target.name]:
event.target.type === "checkbox"
? event.target.checked
: event.target.value
});
setData(update);
return update;
}
if (typeof maybeEvent === "object") {
const [delta, shouldReplaceState] = args;
const update = shouldReplaceState
? middleware(delta)
: middleware({ ...data, ...delta });
setData(update);
return update;
}
const [name, value] = args;
const update = middleware({
...data,
[name]: value
});
setData(update);
return update;
};
return [data, onChange];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment