I’m trying to create a hook that fires a timer every second and updates some state in the component. A part of this state is a counter (how often the timer ran basically) and I’m a little stuck on how to swap!
vs reset!
state in an effect so to say. I guess with state this isn’t really intended to work so I also looked into refs, which I think would work but then again that comes with other inconveniences.
(rum/use-effect! (fn []
(let [timer (js/setInterval #(do (js/console.log :secs-passed secs-passed)
(set-now! (c-util/server-now))
(set-secs-passed! (inc secs-passed)))
1000)]
(fn cleanup-timer [] (js/clearInterval timer))))
[something])
Another approach I’ve seen is to just not use setInterval and instead use a timeout and have the effect run every time the component is updated
Thinking about it a bit more, that might actually just do the job
Yeah, that works. Still a little weird to do it this way instead of only having the effect run once. I guess I could somehow write a custom hook that passes the number of times the interval ran to a callback or something like that?
also wow, https://www.react-spring.io/ looks like it’s come a long way since I last looked at it
pretty excited to play with it some day
I think the proper approach is to setInterval in useEffect and return a function that will cancel it. In the timer callback you can use the setter of useState to update.
I’m using react spring currently, it’s neat but I would wish for something even more high level.
Regarding useEffect, I think you need to be explicit and pass in an empty dependency array to make it work just on mount, otherwise it will fire on every render...
So the code above uses the setter of state (`set-secs-passed!` ) but the issue is that the (inc secs-passed)
captures the value of the first render (`secs-passed` is also state)
@martinklepsch set-secs-passed!
will support taking a function, so (set-secs-passed! inc)
(assuming it works like react/setState
)
oh what, really? did not know!
@dominicm thanks for pointing that out, didn’t realize 🙂
@martinklepsch Unlike swap!
it doesn't take varargs :( but it's good for this use-case.
helix's use-state does 😉