Last active
September 24, 2024 12:40
-
-
Save 9paradox/992629079ebffb9736675c2730db0a4d to your computer and use it in GitHub Desktop.
Easy to use Generic Typescript React custom Hook for Handling multiple inputs and saving state for properties of type or object.
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
import react, { useState } from "react"; | |
const usePartialState = <T extends Partial<T>>(): [T | {}, (fieldName: string, value: any) => void, (state: T) => void] => { | |
const [state, setState] = useState<T | {}>({}); | |
const setStateByFiled = (fieldName: string, value: any) => { | |
setState(_s => { | |
return { | |
..._s, | |
[fieldName]: value, | |
}; | |
}); | |
} | |
const setEntireState = (data: T) => { | |
setState(data); | |
} | |
return [ | |
state, | |
setStateByFiled, | |
setEntireState | |
]; | |
} | |
export default usePartialState; |
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
type MyExample = { | |
myId: number; | |
someTitle: string; | |
}; | |
interface MyExampleState extends Partial<MyExample> { } | |
const MyComponent: React.FC = () => { | |
const [exampleState, setExampleStateByFiled, setExampleState] = usePartialState<MyExampleState>(); | |
const clearAll = () => { | |
setExampleState({}); | |
} | |
return ( | |
<div> | |
<p>{exampleState?.myId} | {exampleState?.someTitle}</p> | |
<button onClick={() => setExampleStateByFiled("myId", 1)}>Change Id</button> | |
<button onClick={() => setExampleStateByFiled("someTitle", "hey everyone!")}>Change title</button> | |
<button onClick={clearAll}>Clear all</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment