Created
March 24, 2020 18:45
-
-
Save ripter/5e641ad02f9cb75e1c348c1c9772d4cf to your computer and use it in GitHub Desktop.
simple validation hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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