Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix #192 - Fix form async initialValues #193

Merged
merged 2 commits into from
Jan 20, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/components/Form/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import FormToggle from './FormToggle'
import FormTree from './FormTree'
import { FieldValues, UseFormMethods } from 'react-hook-form/dist/types/form'
import { FormProvider, SubmitHandler, useForm } from 'react-hook-form'
import React, { ReactNode, RefObject, useImperativeHandle } from 'react'
import React, {
ReactNode,
RefObject,
useEffect,
useImperativeHandle
} from 'react'

const useStyles = createUseStyles({
container: {
Expand All @@ -35,11 +40,21 @@ export function Form<Model>({
}: FormProps<Model>) {
const classes = useStyles()
const methods = useForm({ defaultValues: initialValues, mode: 'onBlur' })
const { reset } = methods

const { handleSubmit } = methods

useImperativeHandle(formRef, () => methods)

useEffect(() => {
/**
* Form must be reset with initialValues if they are fetched asynchronously because the
* initialValues are only passed into useForm once. Without the reset, defaultValues will
* always be an empty object.
*/
reset(initialValues)
}, [initialValues, reset])

return (
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)}>
Expand Down