purescriptfrppurescript-halogen

How to chain actions in purescript (or maybe defer action after rendering)


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 ?


Solution

  • 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)