Skip to content

Commit

Permalink
Merge pull request #31 from rzane/fix-use-mounted
Browse files Browse the repository at this point in the history
The entire ref object needs to be returned from `useMounted`
  • Loading branch information
rzane authored Oct 1, 2020
2 parents a59bf27 + 1aa50c6 commit 31192ea
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/useSubmit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function useSubmit<Value, Result>(
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);
}
});
}
11 changes: 8 additions & 3 deletions src/useValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,17 @@ export function useValidation<Value, Result>(
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);
}
});

Expand Down
10 changes: 5 additions & 5 deletions src/utilities/useMounted.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { useRef, useEffect } from "react";
import { useRef, useEffect, MutableRefObject } from "react";

export function useMounted(): boolean {
const ref = useRef<boolean>(true);
export function useMounted(): MutableRefObject<boolean> {
const isMounted = useRef<boolean>(true);

useEffect(() => {
return () => {
ref.current = false;
isMounted.current = false;
};
}, []);

return ref.current;
return isMounted;
}
9 changes: 9 additions & 0 deletions test/utilities/useMounted.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});

0 comments on commit 31192ea

Please sign in to comment.