From 1aa50c6440db40b85739ca77d7618bfdf4dcc177 Mon Sep 17 00:00:00 2001 From: Ray Zane Date: Thu, 1 Oct 2020 15:39:42 -0400 Subject: [PATCH] The entire ref object needs to be returned from `useMounted`, otherwise it will not update --- src/useSubmit.ts | 2 +- src/useValidation.ts | 11 ++++++++--- src/utilities/useMounted.ts | 10 +++++----- test/utilities/useMounted.test.ts | 9 +++++++++ 4 files changed, 23 insertions(+), 9 deletions(-) create mode 100644 test/utilities/useMounted.test.ts diff --git a/src/useSubmit.ts b/src/useSubmit.ts index 32d2a36..c844e91 100644 --- a/src/useSubmit.ts +++ b/src/useSubmit.ts @@ -39,7 +39,7 @@ export function useSubmit( const result = await form.validate({ touch: true }); if (result.valid) await fn(result.value); } finally { - if (isMounted) form.setSubmitting(false); + if (isMounted.current) form.setSubmitting(false); } }); } diff --git a/src/useValidation.ts b/src/useValidation.ts index 3b9026e..7133d4a 100644 --- a/src/useValidation.ts +++ b/src/useValidation.ts @@ -38,12 +38,17 @@ export function useValidation( const result = await fn(form.value); const errors = result.valid ? undefined : result.error; - if (isMounted) form.setError(errors); - if (isMounted && opts.touch) form.setTouched(getAllTouched(errors)); + if (isMounted.current) { + form.setError(errors); + + if (opts.touch) { + form.setTouched(getAllTouched(errors)); + } + } return result; } finally { - if (isMounted) form.setValidating(false); + if (isMounted.current) form.setValidating(false); } }); diff --git a/src/utilities/useMounted.ts b/src/utilities/useMounted.ts index 752a94b..4c34cd2 100644 --- a/src/utilities/useMounted.ts +++ b/src/utilities/useMounted.ts @@ -1,13 +1,13 @@ -import { useRef, useEffect } from "react"; +import { useRef, useEffect, MutableRefObject } from "react"; -export function useMounted(): boolean { - const ref = useRef(true); +export function useMounted(): MutableRefObject { + const isMounted = useRef(true); useEffect(() => { return () => { - ref.current = false; + isMounted.current = false; }; }, []); - return ref.current; + return isMounted; } diff --git a/test/utilities/useMounted.test.ts b/test/utilities/useMounted.test.ts new file mode 100644 index 0000000..f67548e --- /dev/null +++ b/test/utilities/useMounted.test.ts @@ -0,0 +1,9 @@ +import { renderHook } from "@testing-library/react-hooks"; +import { useMounted } from "../../src/utilities/useMounted"; + +test("useMounted", () => { + const { result, unmount } = renderHook(() => useMounted()); + expect(result.current.current).toBe(true); + unmount(); + expect(result.current.current).toBe(false); +});