Local modifications to ClusterLabs/Anvil by Alteeve
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.

35 lines
860 B

import { Dispatch, SetStateAction, useMemo, useState } from 'react';
import useProtect from './useProtect';
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 { protect: defaultProtect } = useProtect();
const [state, setState] = useState<S>(initialState);
const pfn = useMemo(
() => protect ?? defaultProtect,
[defaultProtect, protect],
);
return [
state,
(...args: SetStateParameters<S>): SetStateReturnType<S> =>
pfn(setState, ...args),
];
};
export default useProtectedState;