Untitled
unknown
javascript
a year ago
1.0 kB
8
Indexable
import { useState, useCallback } from 'react';
type UseAdvancedStateProps<T> = {
[K in keyof T]: T[K];
};
type UseAdvancedStateReturn<T> = {
values: {
[K in keyof T]: T[K];
};
onChange: {
[K in keyof T]: (newValue: T[K]) => void;
};
};
function useAdvancedState<T extends Record<string, any>>(initialState: UseAdvancedStateProps<T>): UseAdvancedStateReturn<T> {
const [state, setState] = useState(initialState);
const handlers = Object.keys(initialState).reduce((acc, key) => {
acc[key as keyof T] = useCallback(
(newValue: any) => {
setState(prevState => ({
...prevState,
[key]: newValue,
}));
},
[key]
);
return acc;
}, {} as UseAdvancedStateReturn<T>['onChange']);
return {
values: state,
onChange: handlers,
};
}
const { values, onChange } = useAdvancedState({
name: '',
age: 0,
});
console.log(values.name);
console.log(values.age);
onChange.name('John Doe');
onChange.age(30);
Editor is loading...
Leave a Comment