1

I'm learning Halogen at the moment but I have a hard time finding how to chain actions. Let's say I have a simple article list component. I also have an "add" button to create a new article to be edited in place in the list.

My approach would be to bind an AddArticle action to the onClick action of the button. In the handleAction function, I'd add a new empty article at the end of the article list model. Then I´d like to scroll to this newly created article. That's where I'm lost. To scroll to this newly created article, I'd have to have a ref to the new article, but it has not been redered yet. So here's the precise question:

How could I chain the two Effects of creating the new article (modify_ the state of the component) and the scrolling to this newly created element ?

amaille
  • 55
  • 7
  • I never used Halogen myself, so I'm not sure, but I would try to send another message after, like, a 1ms delay. I'm sure Halogen must have a way to launch async effects that produce messages. – Fyodor Soikin Sep 25 '22 at 16:39
  • Sure I could do that but that's so hacky... – amaille Sep 26 '22 at 05:43

1 Answers1

2

In Halogen, whenever you modify the state of a component, it immediately re-renders. Halogen doesn't try to do anything clever with batching renders or anything like that, exactly so the behaviour is predictable and reliable for situations like this.

So here, you'd write it the way you described, pretty much:

handleAction = case _ of
  AddArticle -> do
    H.modify_ ?addArticle
    ref <- H.getHTMLElementRef ?refName
    H.liftEffect (?scrollTo ref)
gb.
  • 4,629
  • 1
  • 20
  • 19
  • Oh ! That is weird. I'll try it as soon as I can get back on the project. I hadn't even tried it since I believed that HalogenM is a State monad, so threading the state from computation to computation, getting the final state then re-rendering with the render function. – amaille Sep 27 '22 at 13:26
  • `HalogenM` has an instance of `MonadState`, but it's not actually `State` or even a transformer stack using `StateT`. It's a `Free`-based monad that is interpreted by Halogen's "driver", but that's a whole other can of worms! – gb. Sep 27 '22 at 17:51