Skip to content

bug: Stale event handlers with Range #1010

@mastercactapus

Description

@mastercactapus

It seems that when using app.Range event handlers remain stale, even when the underlying data updates.

Example app demonstrating problem
package main

import (
	"log"
	"net/http"

	"github.com/maxence-charriere/go-app/v10/pkg/app"
)

type hello struct {
	app.Compo

	names []string
}

func NewHello() *hello {
	return &hello{
		names: []string{"foo", "bar", "baz", "qux"},
	}
}

func (h *hello) Render() app.UI {
	return app.Div().Body(
		app.Range(h.names).Slice(func(i int) app.UI {
			name := h.names[i]
			return app.Button().Text(name).OnClick(func(ctx app.Context, e app.Event) {
				app.Log("clicked", name)
			})
		}),
		app.Hr(),
		app.Button().Text("Shift").OnClick(func(ctx app.Context, e app.Event) {
			h.names = append(h.names[1:], h.names[0])
			ctx.Update()
		}),
	)
}

func main() {
	// Components routing:
	app.Route("/", func() app.Composer { return NewHello() })
	app.RunWhenOnBrowser()

	// HTTP routing:
	http.Handle("/", &app.Handler{
		Domain:      "bugreport",
		Name:        "Range Event Bug",
		Description: "An Hello World! example",
	})

	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

Steps to reproduce:

  1. Compile and run the example application
  2. Click foo and see clicked foo in the console
  3. Click Shift and observe that the button text shifts
  4. Click the bar button and see it still says clicked foo in the console

The button below will "shift" the slice and the buttons update as expected. However, it appears the original click handlers are used, rather than the new ones.

I expected that the click handlers would update along with everything else.

A workaround is to embed data in the DOM and pull it back out in the event handler, but is tricky with structs or other complex types that can't be serialized easily.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions