-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3721 from marmelab/fix-forms-dirty-state-after-re…
…cord-initialization [RFR] Fix Form Become Dirty After Record Initialization
- Loading branch information
Showing
3 changed files
with
15 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,32 @@ | ||
import { useEffect } from 'react'; | ||
import { useForm } from 'react-final-form'; | ||
|
||
/** | ||
* Restore the record values which should override any default values specified on the form. | ||
*/ | ||
const useInitializeFormWithRecord = (form, record) => { | ||
const useInitializeFormWithRecord = record => { | ||
const form = useForm(); | ||
|
||
useEffect(() => { | ||
if (!record) { | ||
return; | ||
} | ||
|
||
const registeredFields = form.getRegisteredFields(); | ||
|
||
// react-final-form does not provide a way to set multiple values in one call. | ||
// Using batch ensure we don't get rerenders until all our values are set | ||
form.batch(() => { | ||
Object.keys(record).forEach(key => { | ||
form.change(key, record[key]); | ||
// We have to check the record key is actually registered as a field | ||
// as some record keys may not have a matching input | ||
if (registeredFields.some(field => field === key)) { | ||
form.change(key, record[key]); | ||
form.resetFieldState(key); | ||
} | ||
}); | ||
}); | ||
}, []); // eslint-disable-line | ||
}, [form, record]); | ||
}; | ||
|
||
export default useInitializeFormWithRecord; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters