setValue doesn't update an object properly, e.g. dates
See original GitHub issueDescribe the bug
In one of my forms I use a “complex” object to store some data rather than plain number and text fields. During updating of the form I set this object using setValue
. However, it is not updating properly. For example, the date property isn’t updated.
This is the data structure I’m storing in the form:
const defaultValues = {
name: null,
userData: {
userId: "abc",
date: new Date("2021-06-15"),
}
};
Note that userData.date
is a Date
object.
Updating the form manually use setValue
does not work as expected:
const setUserData = () => {
setValue("userData", {
userId: "1234",
date: new Date("2021-12-15")
});
};
This will only update userData.userId
while userData.data
remains the old value (June instead of December)
To Reproduce Steps to reproduce the behavior:
This is best described using the Codesandbox: https://codesandbox.io/s/currying-forest-yps06?file=/src/App.js
- The form has some default values. One is an object
userData
that contains two values:userId
anddate
. TheuserId
is a simple string while thedate
value is aDate
object. The current form values are shown in the page as a JSON string for easier debugging. - When pressing the button “Update User Data” the
userData
object is updated using react-hook-form’ssetValue
. However, only theuserId
value is set, thedate
value is completely ignored.
I have tested this using just strings and it works as expected. The problem seems to appear only if a Date object is embedded in another object as in my example.
Codesandbox link https://codesandbox.io/s/currying-forest-yps06?file=/src/App.js
Expected behavior
I would expect the whole userData
object to update with the new values. Specifically the date
, not just the userId
.
Additional context I’m using react-hook-form 7.9.0
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
This is a problem with
registration
in general. Reac Hook Form is based on input registration. In your example:This is the only input get registered:
<input {...register("firstName")} placeholder="First Name" />
so hook form registered those inputs on your behalf:
We couldn’t predict it’s a single input or group inputs, so we actually registered two inputs
then when you invoke
setValue
but targeted as a single input, it confused hook form on which field to update.Solutions
always prefer to register your
inputs
, even custom register will help. in your case,reigster('userData')
to avoid this issueI will do some more investigation on this and see if we can improve on this before we close the issue.
found a solution for this.