A custom hook that make things easier with object state.
function useObjectState(defaultValue = {},defaultFieldValue = null) {
const [obj, setObj] = useState(defaultValue);
const update = (key, value) => {
setObj({ ...obj, [key]: value });
};
const get = (key, defaultValue=null) => {
if(!key)return obj;
return obj[key] ?? defaultValue ?? defaultFieldValue;
};
return [get, update, setObj];
}
Example:
function SomeForm({defaultData}){
const [get,update]=useObjectState(defaultData, '');
return <form>
<input value={get('name','John Doe')} onChange={(e)=>update('name',e.target.value)} />
<input value={get('address')} onChange={(e)=>update('address',e.target.value)} />
...
</form>
}
Thank you all! Please feel free to leave any comments.
Top comments (0)