Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

view doesn't update when changing state in setInterval #243

Closed
Athlon64 opened this issue Mar 2, 2023 · 3 comments
Closed

view doesn't update when changing state in setInterval #243

Athlon64 opened this issue Mar 2, 2023 · 3 comments

Comments

@Athlon64
Copy link

Athlon64 commented Mar 2, 2023

Minimal code as follows:

include karax/prelude
import karax/kdom

var v = 10
proc update() =
  v += 10
  # redraw()
discard setInterval(update, 200)

proc main(): VNode =
  result = buildHtml(tdiv):
    text $v

setRenderer main

The view won't get update unless calling redraw() explicitly.

@geotre
Copy link
Collaborator

geotre commented Mar 2, 2023

This is expected. Karax's reactivity model is different to mainstream frameworks (like React and Vue). They implement it by creating reactive state with useState/setState etc. Karax instead reacts to events, similar to things like Elm.

This approach is perhaps simpler and easier to reason about, with the tradeoff being that events need to be wrapped to trigger a redraw. Karax does this for you with dom event handlers, ajax network calls, etc, but you will need to add it for things outside of that (websocket messages, document timing functions).

So the recommended solution would be something like:

include karax/prelude
import karax/kdom except setInterval

proc setInterval(cb: proc(), interval: int): Interval =
  kdom.setInterval(proc =
    cb()
    if not kxi.surpressRedraws: redraw(kxi)
  , interval)

var v = 10
proc update() =
  v += 10
discard setInterval(update, 200)

proc main(): VNode =
  result = buildHtml(tdiv):
    text $v

setRenderer main

Does that all make sense?

@Athlon64
Copy link
Author

Athlon64 commented Mar 2, 2023

I got it. Many thanks, @geotre, your explanation is crystal clear.
By the way, I really think we should put this in the document.

@geotre
Copy link
Collaborator

geotre commented Mar 9, 2023

Thanks for the suggestion @Athlon64, I have added it!

@geotre geotre closed this as completed Mar 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants