From b9d6a473d148521c5e98a259ec8f359ebe3df667 Mon Sep 17 00:00:00 2001 From: Idan Entin Date: Thu, 28 Apr 2022 22:53:34 +0300 Subject: [PATCH] feat: allow passing a value to toggle Closes Closes #365 --- index.js | 10 ++++++++-- index.test.js | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index e39b140..92e68ea 100644 --- a/index.js +++ b/index.js @@ -6,8 +6,14 @@ module.exports = { const open = useCallback(() => setIsOpen(true), []); const close = useCallback(() => setIsOpen(false), []); - const toggle = useCallback(() => setIsOpen(state => !state), []); + const toggle = useCallback((toSet) => { + if (typeof toSet === "undefined") { + setIsOpen((state) => !state); + } else { + setIsOpen(toSet); + } + }, []); return { isOpen, open, close, toggle }; - } + }, }; diff --git a/index.test.js b/index.test.js index 32de09d..0e86b2f 100644 --- a/index.test.js +++ b/index.test.js @@ -42,3 +42,21 @@ test("should toggle the state", () => { expect(result.current.isOpen).toBe(false); }); + +test("should toggle by given value", () => { + const { result } = renderHook(() => useDisclosure()); + + expect(result.current.isOpen).toBe(false); + + act(() => { + result.current.toggle(false); + }); + + expect(result.current.isOpen).toBe(false); + + act(() => { + result.current.toggle(true); + }); + + expect(result.current.isOpen).toBe(true); +});