useForm - how to set defaultValues dynamically with Storage values

Hello, I’m using the newest UI Kit 2 v.10. I have project config JSON stored in Store. Let’s say it’s like this:
{
“toggleValue” : true,
“selectListValue” : [{“label”:“Group A”,“value”:“Group A”}]
}

Now when I open config page that contains two fields Toggle and Select List for this project I want this stored data be fetched and used as defaultValues. Problem is default values are set before I fetch config JSON from Store. As a result default values are empty.

I don’t want to force users to fill every field of that form contains (I have more then two fields, two are just for example). If they change one field fine, I want entire form data be stored as new JSON.

But now without default values set after submiting form, what is passed as data are only touched / changed fields. So when I use toggle data contains only toggle value but there isn’t selectListValue.

Code:
This is how I’m fetching store data

    const [projectConfigState, setProjectConfigState] = useState(undefined);
    useEffect(() => {
        if (selectedProjectKey) {
            invoke('getProjectConfigState', { selectedProjectKey: selectedProjectKey }).then(setProjectConfigState);
        }
    }, [selectedProjectKey]);

this is how I set default values (based on https://developer.atlassian.com/platform/forge/ui-kit-2/use-form/#defaultvalues) [ and keys names are equivalent to form fields names]

    const { handleSubmit, register, formState, getValues  } = useForm(    
        {
            defaultValues: {
                toggleValue: projectConfigState['comments'].isVisible,
                selectListValue : projectConfigState['comments'].restrictedGroups
            }
        }
    )

at this moment projectConfigState isn’t set yet :frowning: .

How to make useForm wait for that data or force defaultValues to reload after projectConfigState is set? I read about react reset method but it’s not available in forge

1 Like

Hi @ITKobe , useForm does not support loading async values at the moment. An alternative solution for your use case is to fetch the data one level higher and then pass down your form data into the hook. Here’s a brief example:

const ProjectConfig = () => {
    const [defaultFormValues, setDefaultFormValues] = React.useState(null);
    React.useEffect(() => {
       // fetch and set your data here ...
       setDefaultFormValues(data);
    }, []);

   if(defaultFormValues) {
       return <ConfigForm defaultFormValues={defaultFormValues} />
   }
   return <Spinner />
    
}

const ConfigForm = ({defaultFormValues}) => {
    const {register} = useForm({defaultValues: defaultFormValues});
    return <Form>// your form here ... </Form>
}


2 Likes