You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
26 lines
664 B
26 lines
664 B
2 years ago
|
import { Dispatch, SetStateAction, useState } from 'react';
|
||
|
|
||
|
type SetStateFunction<S> = Dispatch<SetStateAction<S>>;
|
||
|
|
||
|
type SetStateParameters<S> = Parameters<SetStateFunction<S>>;
|
||
|
|
||
|
type SetStateReturnType<S> = ReturnType<SetStateFunction<S>>;
|
||
|
|
||
|
const useProtectedState = <S>(
|
||
|
initialState: S | (() => S),
|
||
|
protect: (
|
||
|
fn: SetStateFunction<S>,
|
||
|
...args: SetStateParameters<S>
|
||
|
) => SetStateReturnType<S>,
|
||
|
): [S, SetStateFunction<S>] => {
|
||
|
const [state, setState] = useState<S>(initialState);
|
||
|
|
||
|
return [
|
||
|
state,
|
||
|
(...args: SetStateParameters<S>): SetStateReturnType<S> =>
|
||
|
protect(setState, ...args),
|
||
|
];
|
||
|
};
|
||
|
|
||
|
export default useProtectedState;
|