Skip to content

Instantly share code, notes, and snippets.

@ripter
Created March 24, 2020 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ripter/5e641ad02f9cb75e1c348c1c9772d4cf to your computer and use it in GitHub Desktop.
Save ripter/5e641ad02f9cb75e1c348c1c9772d4cf to your computer and use it in GitHub Desktop.
simple validation hook
export function useValidationHook(defaultItemState: Partial<KeywordAdItem>) {
// Allow partial a partial state to be used as the default/inital render.
let defaultState = {...DEFAULT_STATE};
if (defaultItemState) {
Object.assign(defaultState.item, defaultItemState);
}
return useReducer((state: State, action: Action) => {
const { field, value } = action;
// Create a shallow copy of the old data and add/repace the new value.
const newState = { ...state };
// Create a new shallow copy of the item object.
// Use assign to set the field:value pair.
newState.item = Object.assign({}, state.item, {
[field]: value,
});
// To be valid:
// 1. All the values must be defined.
newState.isValid = Object.values(newState.item).every(isDefined);
return newState;
}, defaultState);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment