2
votes

Given a really simple increment component in something like React:

class Increment extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      value: props.value
    }
  }

  componentDidMount() {
    setInterval(() => {
      this.setState(({ value }) => ({ value: value + 1 }))
    }, 1000);
  }

  render(){
    return (
      <p>{ this.state.value }</p>
    );
  }
}


ReactDOM.render(<Increment value={0} />, document.getElementById('root'))

How does this translate to Purescript's Halogen? Looking through various things online, I've yet to find any example I could work into a prototype of my own. I am aware of Effect.Time which exposes setInterval, but how would I use this to trigger of something that would let me update the state (in a controlled action, via handleAction).

I am trying to move an application away from Elm and over to Halogen, and in that application it relies on the subscriptions function for a key bit of functionality to update the application state that doesn't correlate with direct user input. If Halogen has a similar bit of functionality (I have seen subscribe, though that seems to relate to communication between parent/child components, I may have misunderstood this though...) it would be good to be pointed towards it.

1

1 Answers

4
votes

Here is a counter example written in halogen, the code is at purescript-halogen-storybook example.

To make it auto increment, you can add a self loop function in the initialize handler.

loop = 
  H.liftAff $ Aff.delay $ Aff.Milliseconds 1000.0
  H.modify_ \s -> s { value = s.value + 1 }
  loop

handleAction Initialize = loop

Check the official lifecycle example to see how to use initialize.