Created
April 21, 2023 07:24
-
-
Save chihabhajji/b253b366dded23d7d791fc6c083459f8 to your computer and use it in GitHub Desktop.
Generic form handler to update the state
This file contains 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
type NonArrayFunctionKeys<T> = { | |
[K in keyof T]-?: T[K] extends Function | unknown[] ? never : K | |
}[keyof T]; | |
const handleInputChange = <TKey extends NonArrayFunctionKeys<User>, TValue>( | |
value: TValue, | |
name: TKey, | |
// setStateCallback: React.Dispatch<React.SetStateAction<User>> | |
) => setProfile((prev) => ({...prev, [name]: value})); | |
type KeysMatching<T, V> = { [K in keyof T]-?: T[K] extends V ? K : never }[keyof T]; | |
const handleArrayChanged = <TKey extends KeysMatching<User, unknown[]>, TValue extends string>( | |
value: TValue, | |
name: TKey, | |
// setStateCallback: React.Dispatch<React.SetStateAction<User>> | |
) => { | |
setProfile((preProfile) => { | |
const updated = {...preProfile}; | |
if (Array.isArray(updated[name]) && updated[name].includes(value)) { | |
updated[name] = updated[name].filter((item) => item !== value); | |
} else { | |
updated[name] = [...(updated[name] ?? []), value]; | |
} | |
return updated; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment