From e2c0c7b12215f2144c73f0fda165ec81d9057a5f Mon Sep 17 00:00:00 2001 From: chornos13 Date: Thu, 18 Feb 2021 12:02:40 +0700 Subject: [PATCH] feat(hooks): add feature reset useToggle --- .../useToggle/__test__/useToggle.test.ts | 27 +++++++++++++++++++ src/hooks/useToggle/useToggle.tsx | 11 +++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/hooks/useToggle/__test__/useToggle.test.ts b/src/hooks/useToggle/__test__/useToggle.test.ts index 7db85a9..66cc579 100644 --- a/src/hooks/useToggle/__test__/useToggle.test.ts +++ b/src/hooks/useToggle/__test__/useToggle.test.ts @@ -117,4 +117,31 @@ describe('basic function', () => { ...newState, }) }) + + test('should reset state to initial value when call reset function', () => { + // arrange + const initialState = { + anyInitialData: 'anyInitialValue', + } + const initialToggle = false + const { result } = renderHook(() => + useToggle({ + initialToggle, + initialState, + }), + ) + + // act + act(() => { + result.current.toggle({ + anyInitialData: 'anyChangedValue', + }) + + result.current.reset() + }) + + // assert + expect(result.current.state).toEqual(initialState) + expect(result.current.isToggled).toEqual(initialToggle) + }) }) diff --git a/src/hooks/useToggle/useToggle.tsx b/src/hooks/useToggle/useToggle.tsx index cb7af61..b0ef167 100644 --- a/src/hooks/useToggle/useToggle.tsx +++ b/src/hooks/useToggle/useToggle.tsx @@ -40,11 +40,20 @@ function useToggle(configs?: UseToggleConfigs) { function untoggle(state?: T | any) { setState(TOGGLE_ACTION_TYPE.UNTOGGLE, state) } + + function reset() { + setState( + initialToggle ? TOGGLE_ACTION_TYPE.TOGGLE : TOGGLE_ACTION_TYPE.UNTOGGLE, + initialState, + ) + } + return { isToggled, - state, + state: state as T, toggle, untoggle, + reset, } }, [counter]) }