package main
import (
"context"
"fmt"
"time"
"github.com/go-mizu/mizu/view/sync"
)
type Todo struct {
Title string `json:"title"`
Completed bool `json:"completed"`
}
func main() {
// Create client
client := sync.New(sync.Options{
BaseURL: "http://localhost:8080/_sync",
Scope: "user:demo",
OnSync: func(cursor uint64) {
fmt.Printf("Synced to cursor %d\n", cursor)
},
OnOnline: func() {
fmt.Println("Connected!")
},
OnOffline: func() {
fmt.Println("Offline - changes will sync later")
},
})
// Start sync
ctx := context.Background()
client.Start(ctx)
defer client.Stop()
// Create collection
todos := sync.NewCollection[Todo](client, "todo")
// Log changes reactively
sync.NewEffect(func() {
fmt.Printf("Todo count: %d\n", todos.Count())
})
// Create some todos
todos.Create("1", Todo{Title: "Learn Go"})
todos.Create("2", Todo{Title: "Build sync app"})
todos.Create("3", Todo{Title: "Deploy"})
// Mark one complete
entity := todos.Get("1")
todo := entity.Get()
todo.Completed = true
entity.Set(todo)
// Find incomplete
incomplete := todos.Find(func(t Todo) bool {
return !t.Completed
})
fmt.Printf("\nIncomplete todos:\n")
for _, e := range incomplete {
fmt.Printf(" - %s\n", e.Get().Title)
}
// Keep running to see sync happen
time.Sleep(3 * time.Second)
}