Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How not to duplicate a method using react hooks?

I have a hook called useAnalytics that I use to send events from my Analytics.
Inside it I have two methods:

const fireScreenDisplayed = (props = {}) => {
  _checkScreenValidity()
  if (checkDone && done && !props.force) return
  setDone(true)
  publishCdmEvent(_buildEvent('ScreenDisplayed', props))
}

const fireScreenCompleted = (props = {}) => {
  _checkScreenValidity()
  if (checkDone && done && !props.force) return
  setDone(true)
  publishCdmEvent(_buildEvent('ScreenDisplayed', props))
}

As you can see they are the same changing only the name,
I made it so when I call the method in a component I can pass different parameters in the useAnalytics hook.

const { fireScreenDisplayed } = useAnalytics(SCREENS.START)
const { fireScreenCompleted } = useAnalytics(SCREENS.COMPLETED)

In this case I want to pass two different constants SCREENS.START and SCREENS.COMPLETED

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As a way to improve my code I would like to find a way to not duplicate these methods, have only one inside my Hook and be able to pass different parameters in my component.

How do I do that?

>Solution :

Based on what you’ve shown, i think you just need to delete one of the functions. If necessary, you can reference the remaining function multiple times.

const useAnalytics = () => {
  const handler = (props = {}) => {
     _checkScreenValidity()
     if (checkDone && done && !props.force) return
     setDone(true)
     publishCdmEvent(_buildEvent('ScreenDisplayed', props))
   }

  return {
    fireScreenCompleted: handler,
    fireScreenDisplayed: handler
  }
}

You mentioned wanting to be able to pass a constant into the hook, but i don’t know what that constant is supposed to do. If you edit your question to include more details, i’ll try to include that in my answer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading