From e56fcfd8801f17bf1c94ac0b755bc3341bc9e86c Mon Sep 17 00:00:00 2001 From: Tsu-ba-me Date: Tue, 14 Feb 2023 18:20:56 -0500 Subject: [PATCH] fix(striker-ui): add default protect() to useProtectedState --- striker-ui/hooks/useProtectedState.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/striker-ui/hooks/useProtectedState.ts b/striker-ui/hooks/useProtectedState.ts index 019fc9c0..f486c201 100644 --- a/striker-ui/hooks/useProtectedState.ts +++ b/striker-ui/hooks/useProtectedState.ts @@ -1,4 +1,6 @@ -import { Dispatch, SetStateAction, useState } from 'react'; +import { Dispatch, SetStateAction, useMemo, useState } from 'react'; + +import useProtect from './useProtect'; type SetStateFunction = Dispatch>; @@ -8,17 +10,24 @@ type SetStateReturnType = ReturnType>; const useProtectedState = ( initialState: S | (() => S), - protect: ( + protect?: ( fn: SetStateFunction, ...args: SetStateParameters ) => SetStateReturnType, ): [S, SetStateFunction] => { + const { protect: defaultProtect } = useProtect(); + const [state, setState] = useState(initialState); + const pfn = useMemo( + () => protect ?? defaultProtect, + [defaultProtect, protect], + ); + return [ state, (...args: SetStateParameters): SetStateReturnType => - protect(setState, ...args), + pfn(setState, ...args), ]; };