How to change Form initialValues and Fields based on selection in ReactJS?

ebanban208 注册会员
2023-01-25 21:51

This is not quite correct approach, and it's not good idea for me to change set of fields in a form on-the-fly - you'll have problems supporting your own tangled code, this useEffect is pure mess.

Keep in mind that form data you use for UI may differ from data you send to backend and can be transformed right before you make a request. Actually initialValues is for initializing your form and should not be changed from inside the form. I'd create universal set of field.

For example, I'd change data initial data like this

// read-only array to render Select, add as much item as you like.
// In general, since it's just an array for options,
// it can be safely extracted to external constant
// and may not present in initialData. 
Categories: [
  name 'Planers',
  selected: true,
   name: 'Plants'
Category: 'Planers', // since selected is true 
Planters: {
  "Material": "",
  "Build": "",
  "PlanterHeight": "",
  "PlanterWidth": ""
Plants: {
  "Light": "",
  "Watering": "",
  "Maintenance": "",
  "WhereToGrow": "",

And then in your form

// ...
const { values, handleChange, handleBlur } = useFormikContext();

and in the same component two or more sets of fields. Each set is rendered according to SelectedCategory value. There's no need to change or reset values in sets of fields when SelectedCategory changes - you can remove or reset the fields on the stage of sending the data.

if (values.SelectedCategory === 'Planers') {
  // render set of fields for Planers
if (values.SelectedCategory === 'Plants') {
  // render set of fields for Plants

And onSubmit you can transform your filed values as you like:

      const transformedDataForAsyncRequest = yourCustomDataTransducer(values);
        method: 'post',
        data: transformedDataForAsyncRequest
        .then(() => {resetForm()})
        .catch((e) => {console.log(e)})