reactjsreact-final-form

Make API call after form selection with React Final Form


I have a form with two dropdowns. The second dropdown list of options is returned by an API and depends on what the user selected in the first dropdown. How can I do this with React Final Form? Basically this involves:

  1. The user selects an option from the first dropdown. This list is hardcoded
  2. I make an API call and pass the selected option, the backend returns the list of options for the second dropdown
  3. I update the form with the backend reponse

I can't wrap my head around how to do this.


Solution

  • If you dont create your own custom Select component, you can use something like this:

    import { useFormState } from 'react-final-form';
      const { values } = useFormState();
    
      const [selectOptions2, setSelectOptions2] = useState([]);
    
      const fetchOptions = useCallback(async () => {
        try {
          const { data } = await getOptions2();
          if (data.options) {
            setSelectOptions2(data.options);
          }
        } catch (e) {
          console.error(r);
        }
      }, [values.selectedOption1]);
    

    And then use selectOptions2 as options for second Select.