0

The following component includes an useEffect that should run on mount and then cleanup the effect:

const Group = ({
  children,
  accessor,
  disabled = false,
}: {
  children: React.ReactNode
  accessor: Accessor
  disabled?: boolean
}) => {
  const dispatch = useEditorDispatch()

  React.useEffect(() => {
    if (accessor.length === 1 && field === 'audienceExtension') return
    const attribute = `-${field}`
    console.log(`on mount ${accessor}`)
    dispatch({
      type: 'setError',
      payload: {
        message: 'is empty',
        attribute,
        accessor,
      },
    })

    return () => {
    console.log(`on unmount ${accessor}`)
      dispatch({
        type: 'setError',
        payload: { message: null, attribute, accessor },
      })
    }
  }, [])

The component tree is build by including Groups inside Groups. When a Group mounts I correctly see the accessor value (incremental) but whenever a Group unmounts the console logs the latest accessor value so not the one related to the unmounted Group. I was expecting the returned closure to capture the props of each Group and then run the dispatch with the correct values but that's not the case.

1 Answers1

0

You are referencing the accessor value that exists outside the function, and getting whatever value it happens to have at unmount time. To capture the on-mount value, I'd define a variable at the start of useEffect, and use that in the return funtion - add a const accessorAtStartOfEffect = accessor right next to const attribute.

Toms Mikoss
  • 9,097
  • 10
  • 29
  • 41