Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: WatchEffect is overriding the previous function #1

Open
otaxhu opened this issue Dec 4, 2023 · 0 comments
Open

Bug: WatchEffect is overriding the previous function #1

otaxhu opened this issue Dec 4, 2023 · 0 comments

Comments

@otaxhu
Copy link

otaxhu commented Dec 4, 2023

So I tried the next code (minimal representation) and got an unexpected behaviour:

main.go:

package main

import (
	"bufio"
	"fmt"
	"os"

	"github.com/nasan016/gofer"
)

func main() {

	count1 := gofer.Ref(0)
	count2 := gofer.Ref(0)

	gofer.WatchEffect(func() {
		// Operations that I want to execute only if count1 changes
		fmt.Println("count1 = ", count1.GetValue())
	})

	// BUG: This function overrides the previous function
	gofer.WatchEffect(func() {
		// Operations that I want to execute only if count2 changes
		fmt.Println("count2 = ", count2.GetValue())
	})

	scanner := bufio.NewScanner(os.Stdin)
	fmt.Print(">>> ")
	for scanner.Scan() {
		text := scanner.Text()
		if text == "increment count1" {
			count1.SetValue(count1.GetValue() + 2)
		}
		if text == "increment count2" {
			count2.SetValue(count2.GetValue() + 3)
		}
		fmt.Print("\n>>>")
	}
}

What I expected:

I thought that WatchEffect tracks the Refs, but this is not the case, even if I set Ref's value that are not supposed to be tracked by the effect (because this are not inside of the effect), the WatchEffect function is executed anyways. Something like this:

func main() {
	countNotInEffect := gofer.Ref(0)
	gofer.WatchEffect(func () {
		fmt.Println("executing effect")
	})
	// The effect is executed anyways
	countNotInEffect.SetValue(countNotInEffect.GetValue() + 1)
}

Suggested solution:

See vue's watch function, note that takes in an array of reactive dependencies, suggested function signature to mimic the vue's: Watch[T any](deps []*gofer.RefImpl[T], effectFunc func())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant