Skip to content

Commit

Permalink
feat(hooks): add feature reset useToggle
Browse files Browse the repository at this point in the history
  • Loading branch information
chornos13 committed Feb 18, 2021
1 parent 3eba878 commit e2c0c7b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
27 changes: 27 additions & 0 deletions src/hooks/useToggle/__test__/useToggle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
11 changes: 10 additions & 1 deletion src/hooks/useToggle/useToggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,20 @@ function useToggle<T>(configs?: UseToggleConfigs<T>) {
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])
}
Expand Down

0 comments on commit e2c0c7b

Please sign in to comment.