github.com/jgarto/itcv@v0.0.0-20180826224514-4eea09c1aa0d/examples/timer/timer.go (about)

     1  package timer //import "myitcv.io/react/examples/timer"
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"myitcv.io/react"
     8  )
     9  
    10  //go:generate reactGen
    11  
    12  // TimerDef is the definition of the Timer component
    13  type TimerDef struct {
    14  	react.ComponentDef
    15  }
    16  
    17  // TimerState is the state type for the Timer component
    18  type TimerState struct {
    19  	ticker *time.Ticker
    20  
    21  	secondsElapsed float32
    22  }
    23  
    24  // Timer creates instances of the Timer component
    25  func Timer() *TimerElem {
    26  	return buildTimerElem()
    27  }
    28  
    29  // ComponentWillMount is a React lifecycle method for the Timer component
    30  func (t TimerDef) ComponentWillMount() {
    31  	tick := time.NewTicker(time.Second * 1)
    32  
    33  	s := t.State()
    34  	s.ticker = tick
    35  	t.SetState(s)
    36  
    37  	go func() {
    38  		for {
    39  			select {
    40  			case <-tick.C:
    41  				c := t.State()
    42  				c.secondsElapsed++
    43  				t.SetState(c)
    44  			}
    45  		}
    46  	}()
    47  }
    48  
    49  func (t TimerDef) ComponentWillUnmount() {
    50  	t.State().ticker.Stop()
    51  }
    52  
    53  // Render renders the Timer component
    54  func (t TimerDef) Render() react.Element {
    55  	return react.Div(nil,
    56  		react.Div(nil,
    57  			react.S(fmt.Sprintf("Seconds elapsed %.0f", t.State().secondsElapsed)),
    58  		),
    59  	)
    60  }