PrevelteKit

Bitcoin Price

Live price fetched from the Coinbase API with auto-refresh every 60 seconds.

Loading...

How it works

This demo uses p.Get[T]() to fetch JSON, p.SetInterval() for auto-refresh, and lifecycle hooks for setup/teardown.

type PriceResponse struct {
    Data struct {
        Amount   string `js:"amount"`
        Base     string `js:"base"`
        Currency string `js:"currency"`
    } `js:"data"`
}

type BitcoinDemo struct {
    Price       *p.Store[string]
    Symbol      *p.Store[string]
    Loading     *p.Store[bool]
    Error       *p.Store[string]
    stopRefresh func()
}

func (b *BitcoinDemo) OnMount() {
    if p.IsBuildTime { return }
    b.FetchPrice()
    b.stopRefresh = p.SetInterval(60000, func() {
        b.FetchPrice()
    })
}

func (b *BitcoinDemo) OnDestroy() {
    if b.stopRefresh != nil {
        b.stopRefresh()
    }
}

func (b *BitcoinDemo) FetchPrice() {
    b.Loading.Set(true)
    b.Error.Set("")
    go func() {
        resp, err := p.Get[PriceResponse](url)
        if err != nil {
            b.Error.Set("Failed to fetch: " + err.Error())
            b.Loading.Set(false)
            return
        }
        b.Price.Set(resp.Data.Currency + " " + resp.Data.Amount)
        b.Symbol.Set(resp.Data.Base)
        b.Loading.Set(false)
    }()
}