Andrii Radkevych
Andrii Radkevych

Reputation: 3432

componentWillUnmount by using hooks with params dependecies

 useEffect(() => {
    return () => {
      let tb = [...Array(row.length).keys()].map(index => {
        return header.reduce((ob, key) => {
          return {
            ...ob,
            [key]: row[index][key]
          }
        }, {})
      })

      if (dimension) {
        tb = tb.map((entity, index) => {
          return {
            ...entity,
            '': row[index].hdr
          }
        })
      }
      dispatch(change(form, `table.${activeButton}`, tb))
    }
  }, [])

I want to execute some code on component unmount, I know that achieve this you can by using this approach with hooks :

 useEffect(() => {
    return () => {
      // some code here
    }
  }, [])

But in first code snippet I have some values which are not static , and for getting last version of this data , I have to pass it to [row,header], and this is the problem , does it mean that I can't execute this code on unmount ? or exist some another way to make it ?

Upvotes: 1

Views: 70

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281764

The fact that you want to execute code on unmount and access the updated data, you would need to make use of useRef and useEffect

const rowRef = useRef(row);
const headerRef = useRef(header);
useEffect(() => {
    rowRef.current = row;
    headerRef.current = header;
}, [row, header]);
useEffect(() => {
    return () => {
      let tb = [...Array(rowRef.current.length).keys()].map(index => {
        return headerRef.current.reduce((ob, key) => {
          return {
            ...ob,
            [key]: rowRef.current[index][key]
          }
        }, {})
      })

      if (dimension) {
        tb = tb.map((entity, index) => {
          return {
            ...entity,
            '': rowRef.current[index].hdr
          }
        })
      }
      dispatch(change(form, `table.${activeButton}`, tb))
    }
  }, [])

Upvotes: 1

Related Questions