Form: Allow default values updates (#22435)

* Allow default values update in form

* Update packages/grafana-ui/src/components/Forms/Form.story.tsx
This commit is contained in:
Dominik Prokop 2020-02-26 14:17:21 +01:00 committed by GitHub
parent 712253fbee
commit 22ce16cc9b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 13 deletions

View File

@ -1,4 +1,4 @@
import React from 'react';
import React, { useState } from 'react';
import { Legend } from './Legend';
import { withCenteredStory } from '../../utils/storybook/withCenteredStory';
@ -122,17 +122,39 @@ export const basic = () => {
};
export const defaultValues = () => {
const defaultValues = [
{
name: 'Roger Waters',
nested: {
path: 'Nested path default value',
},
radio: 'option2',
select: 'option1',
switch: true,
},
{
name: 'John Waters',
nested: {
path: 'Nested path default value updated',
},
radio: 'option1',
select: 'option2',
switch: false,
},
];
const [defaultsIdx, setDefaultsIdx] = useState(0);
return (
<>
{renderForm({
name: 'Roger Waters',
nested: {
path: 'Nested path default value',
},
radio: 'option2',
select: 'option1',
switch: true,
})}
{renderForm(defaultValues[defaultsIdx])}
<Button
onClick={() => {
setDefaultsIdx(s => (s + 1) % 2);
}}
variant="secondary"
>
Change default values
</Button>
</>
);
};

View File

@ -2,7 +2,7 @@
* This is a stub implementation only for correct styles to be applied
*/
import React from 'react';
import React, { useEffect } from 'react';
import { useForm, Mode, OnSubmit, DeepPartial, FormContextValues } from 'react-hook-form';
import { GrafanaTheme } from '@grafana/data';
import { css } from 'emotion';
@ -27,10 +27,17 @@ interface FormProps<T> {
export function Form<T>({ validateOn, defaultValues, onSubmit, children }: FormProps<T>) {
const theme = useTheme();
const { handleSubmit, register, errors, control } = useForm<T>({
const { handleSubmit, register, errors, control, reset, getValues } = useForm<T>({
mode: validateOn || 'onSubmit',
defaultValues,
defaultValues: {
...defaultValues,
},
});
useEffect(() => {
reset({ ...getValues(), ...defaultValues });
}, [defaultValues]);
const styles = getFormStyles(theme);
return (