Redux-form fires an extra CHANGE action when deleting an element in complex fieldArray

36 views Asked by At

I have a form built with reduxForm which has a nested fieldArray component. In this component, I have two dropdowns. The first determines what will be in the second dropdown.

Here's my solution for that

// Set initial list values when hydrating form
  const setInitialQualifiantTypeList = () => {
    const list: (string | undefined)[] = []
    fields.forEach((qualifiant: any, index: number) => {
      const qualifiantType = fields.get(index).qualifiantType
      list.push(qualifiantType ? `B0${qualifiantType}` : undefined)
    })
    return list
  }

  let qualifiantTypeList = setInitialQualifiantTypeList()

// Change list parameter when changing the type
  const onChangeQualifiantType = (
    qualifiantType: string,
    qualifiant: string,
    name: string,
    index: number
  ) => {
    let newQualifiantTypeList = [...qualifiantTypeList]
    if (qualifiantType === '') {
      newQualifiantTypeList[index] = undefined
    } else {
      newQualifiantTypeList[index] = `B0${qualifiantType}`
      // setQualifiantTypeList(newQualifiantTypeList)
      qualifiantTypeList = newQualifiantTypeList
    }
// If it doesn't match previous type reset the value
    if (qualifiantType !== qualifiant.substring(0, 2)) {
      resetValue(`${name}[${index}].qualifiant`)
    }
  }

qualifiantTypeList gets passed as a prop to my dropdown component which gets the appropriate list.

However, when it comes to the fieldArray part, I lose some data if deleting any of my fields except the last. I've tried fields.remove(index) and even change(form, field, newArray) replacing the entire value, but redux-form fires an extra CHANGE no matter what, making my data go from

[
    {
        "qualifiantType": "94",
        "qualifiant": "1KBC-CA-Q"
    },
    {
        "qualifiantType": "95",
        "qualifiant": "2A"
    },
    {
        "qualifiantType": "96",
        "qualifiant": "3B"
    }
]

to

[
    {
        "qualifiantType": "94",
        "qualifiant": "1KBC-CA-Q"
    },
    {
        "qualifiantType": "96"
    }
]

Form elements before deleting Form elements after deleting

The state I'm looking for does appear in the redux devtools, but an extra CHANGE action gets dispatched and clears it. I've logged my onChangeQualifiantType function and it's not firing during this process, so that's not the cause. Redux devtools showing requested state Redux devtools showing wrong state a couple actions later

How I can I prevent this behavior so as to simply delete the array element and keep everything else?

1

There are 1 answers

0
PaulSusset On

After some digging, turns out it's because the sub-list is an async DB fetch, it renders first with the new answer, the component clears it because it's a dropdown and the value is replaced by the time the data is in place.