Recompose: withHandlers and clearTimeout

Created on 8 Oct 2017  路  2Comments  路  Source: acdlite/recompose

Hi, I need a help with withHandlers hoc. I'm trying to handle a delayed action onMouseEnter with this code. The problem is that clearTimeout(show); doesn't work. Where I'm wrong? Thanks for the help!

<div
  onMouseEnter={() => handleTooltipVisibility('enter')}
  onMouseLeave={() => handleTooltipVisibility('leave')}
>
withHandlers({
  handleTooltipVisibility: props => (action) => {
    const show = () => setTimeout(() => props.setShowTooltip(true), 1000);
    clearTimeout(show);

    if (action === 'enter') {
      show();
    }
    if (action === 'leave') {
      props.setShowTooltip(false);
    }
  },
}),

Most helpful comment

You can use withHandlers as a factory:

withHandlers(
  ({ showTooltip, hideTooltip }) => {
    let timeout = null

    return {
      onMouseEnter: () => () => {
        timeout = setTimeout(showTooltip, 1000)
      },
      onMouseLeave: () => () => {
        clearTimeout(timeout)
        hideTooltip()
      }
    }
  }
)

All 2 comments

You can use withHandlers as a factory:

withHandlers(
  ({ showTooltip, hideTooltip }) => {
    let timeout = null

    return {
      onMouseEnter: () => () => {
        timeout = setTimeout(showTooltip, 1000)
      },
      onMouseLeave: () => () => {
        clearTimeout(timeout)
        hideTooltip()
      }
    }
  }
)

Thanks @deepsweet, it works!

Was this page helpful?
0 / 5 - 0 ratings