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
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.