SolidJSS
SolidJSโ€ข12mo agoโ€ข
10 replies
snorbi

How to extract common reactive code?

I have some common code that I want to use in multiple components, like:
  const [currentTime, setCurrentTime] = createSignal(getCurrentTimeMinutePrecision())

  let timer: NodeJS.Timer
  onMount(() => {
    timer = setInterval(() => {
      const now = getCurrentTimeMinutePrecision()
      if (!now.equals(currentTime())) {
        setCurrentTime(getCurrentTimeMinutePrecision())
      }
    }, 1_000)
  })
  onCleanup(() => clearInterval(timer))

What is the correct way to refactor this code fragment to a separate function and use it from multiple components?
Can I just simply extract it as is, and return the Signal (or only the Accessor in case of my example)?
E.g. what would happen if I call this from inside an effect?
Can I somehow prevent it to be called from an ordinary function?
Thanks.
Was this page helpful?