Skip to content

Commit

Permalink
🐛: reject non-boolean value as a defaultValue for useBoolean (#561 by
Browse files Browse the repository at this point in the history
@luckrnx09)

* fix: reject non-boolean value as a defaultValue for `useBoolean`

* add changeset
  • Loading branch information
luckrnx09 committed Apr 4, 2024
1 parent 7ba7e3a commit 90a33f5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/sharp-donkeys-impress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"usehooks-ts": patch
---

fix: reject non-boolean value as a defaultValue for useBoolean
7 changes: 7 additions & 0 deletions packages/usehooks-ts/src/useBoolean/useBoolean.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,11 @@ describe('useBoolean()', () => {

expect(result.current.value).toBe(false)
})

it('should throw an error', () => {
const nonBoolean = '' as never
expect(() => {
renderHook(() => useBoolean(nonBoolean))
}).toThrow('defaultValue must be `true` or `false`')
})
})
8 changes: 6 additions & 2 deletions packages/usehooks-ts/src/useBoolean/useBoolean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,19 @@ type UseBooleanReturn = {
* Custom hook that handles boolean state with useful utility functions.
* @param {boolean} [defaultValue] - The initial value for the boolean state (default is `false`).
* @returns {UseBooleanReturn} An object containing the boolean state value and utility functions to manipulate the state.
* @throws Will throw an error if `defaultValue` is an invalid boolean value.
* @public
* @see [Documentation](https://usehooks-ts.com/react-hook/use-boolean)
* @example
* ```tsx
* const { value, setTrue, setFalse, toggle } = useBoolean(true);
* ```
*/
export function useBoolean(defaultValue?: boolean): UseBooleanReturn {
const [value, setValue] = useState(!!defaultValue)
export function useBoolean(defaultValue = false): UseBooleanReturn {
if (typeof defaultValue !== 'boolean') {
throw new Error('defaultValue must be `true` or `false`')
}
const [value, setValue] = useState(defaultValue)

const setTrue = useCallback(() => {
setValue(true)
Expand Down

0 comments on commit 90a33f5

Please sign in to comment.