From 9839445df1b21beff981bd88e8e7ea900c79319d Mon Sep 17 00:00:00 2001 From: Jake Harding Date: Mon, 14 Feb 2022 16:43:53 -0700 Subject: [PATCH] Use parse instead of format when calculating checked --- src/Field.test.js | 88 +++++++++++++++++++++++++++++++++++++++++++++++ src/useField.js | 4 +-- 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/src/Field.test.js b/src/Field.test.js index afd0810..cd2381a 100644 --- a/src/Field.test.js +++ b/src/Field.test.js @@ -1249,3 +1249,91 @@ describe("Field", () => { console.error.mockRestore(); }); }); + +it("should support using format/parse with radio controls", () => { + const format = (value) => value && value.toString(); + const parse = (value) => value && parseInt(value, 10); + + const { getByTestId } = render( +
+ {({ handleSubmit }) => ( + + + + + + )} + , + ); + expect(getByTestId("ten").checked).toBe(false); + expect(getByTestId("twenty").checked).toBe(true); + expect(getByTestId("thirty").checked).toBe(false); +}); + +it("should support using format/parse with checkbox controls", () => { + const format = (value) => value && value.map((x) => x.toString()); + const parse = (value) => value && value.map((x) => parseInt(x, 10)); + + const { getByTestId } = render( +
+ {({ handleSubmit }) => ( + + + + + + )} + , + ); + expect(getByTestId("ten").checked).toBe(false); + expect(getByTestId("twenty").checked).toBe(true); + expect(getByTestId("thirty").checked).toBe(true); +}); diff --git a/src/useField.js b/src/useField.js index c6ffa68..1f3e48c 100644 --- a/src/useField.js +++ b/src/useField.js @@ -161,14 +161,14 @@ function useField( get checked() { let value = state.value; if (type === "checkbox") { - value = format(value, name); + value = parse(value, name); if (_value === undefined) { return !!value; } else { return !!(Array.isArray(value) && ~value.indexOf(_value)); } } else if (type === "radio") { - return format(value, name) === _value; + return parse(value, name) === _value; } return undefined; },