Wind: own the lifetime of async data
Use extras/wind for three different jobs: query a snapshot, stream a changing value, or mutate a resource on demand. Give each distinct resource and result type its own comparable key. A struct containing a workspace ID and task ID makes a useful detail key.
Mount a cache and load a snapshot
Section titled “Mount a cache and load a snapshot”client := wind.NewClient()app.OnStop(client.Close)root.Render(wind.Provider(wind.ProviderProps{Client: client}, view))Inside a component, pass a function such as load(ctx context.Context, key string) ([]string, error) directly. Wind runs queries and mutations on the background scheduler and links their contexts to scheduler shutdown. The same client and key identify the shared cache entry.
q := wind.Use("titles", load, wind.Options{ StaleTime: time.Minute, Enabled: wind.Some(true),})if q.IsError { return kitex.Text(q.Error.Error()) }if q.IsLoading { return kitex.Text("Loading…") }return kitex.Textf("%d titles", len(q.Data))IsFetching also covers background refreshes: keep showing cached data while refreshing. Call q.Refetch() to retry. For optional fields, unset Optional[T] means use the default; wind.Some(false) disables the query explicitly. Get() on an optional returns both the value and whether it was set.
Page between results and warm the next page
Section titled “Page between results and warm the next page”opts := wind.Options{ KeepPreviousData: true, StaleTime: time.Minute, RefetchInterval: 30 * time.Second, Retry: 2,}page := wind.Use(pageNumber, loadPage, opts)When the key changes, page.IsPlaceholderData distinguishes the previous page from a real result for the new key. The placeholder is not written to the cache. IsLoading is false while it is shown; use IsFetching for a refresh indicator. A failed new page reports its error instead.
A positive RefetchInterval polls while the hook is enabled and mounted. Ticks during a fetch are skipped, not queued. Unmount or close the client to stop polling. Retry counts additional attempts on returned errors (default zero); panics are not retried. RetryDelay(attempt) receives zero for the first retry. The default waits 1, 2, 4, 8, 16, then 30 seconds; cancellation interrupts the wait.
On focus or navigation intent, call wind.PrefetchQuery(client, nextPage, loadPage, opts) outside render. It starts a background fetch only for missing or stale data and shares in-flight work with Use. The hook’s own StaleTime controls whether it refreshes on mount. Prefetch honors retry settings but does not subscribe or poll; unused results expire after client.GcTime.
Connect a stream
Section titled “Connect a stream”Suppose watch has signature func(context.Context, int) iter.Seq2[int, error] and emits a complete count each time it changes:
counts := wind.UseStream("counts", wind.Stream[int, int]{ Initial: 0, Source: watch, Reduce: wind.Latest[int], RefetchMode: wind.RefetchReplace,})Stream[E, S] folds events of type E into state S. Use Latest for snapshots; for deltas, write a reducer instead. Optional Fetch loads a snapshot before Source starts. The source receives the starting state so it can resume from a cursor. Honor context cancellation and stop when the iterator consumer returns false.
| Reconnect mode | What happens to the previous result? |
|---|---|
RefetchReplace (default) |
Keep it visible until new data replaces it; reduction starts fresh. |
RefetchReset |
Reset to Initial immediately and show loading again. |
RefetchAppend |
Reduce onto the cached state when available. Use a cursor to avoid replaying duplicates. |
Write, then refresh readers
Section titled “Write, then refresh readers”For save(ctx context.Context, title string) (int, error), use a mutation rather than treating a button press as a new query key:
m := wind.UseMutation(save, wind.MutationOptions[string, int]{ OnSuccess: func(_ int, _ string, ctx wind.MutationContext) { ctx.Client.InvalidateQueries("titles") }, },)return kitex.Button(kitex.ButtonProps{ Disabled: m.IsPending, OnPress: func() { m.Mutate("Review notes") },}, kitex.Text("Save"))Read m.Error when m.IsError. Unmounting cancels the mutation context and suppresses subsequent callbacks; your write function must honor the context.
Show a change before the server replies
Section titled “Show a change before the server replies”For a title editor, save the cached title in OnMutate. If there is no cached title, skip the optimistic write; the request still runs.
m := wind.UseMutation(save, wind.MutationOptions[string, int]{ OnMutate: func(title string, ctx wind.MutationContext) (any, error) { prev, ok := wind.GetQueryData[string, string](ctx.Client, "title") if !ok { return nil, nil } wind.SetQueryData(ctx.Client, "title", title) return prev, nil }, OnError: func(_ error, _ string, ctx wind.MutationContext) { if prev, ok := ctx.Rollback.(string); ok { wind.SetQueryData(ctx.Client, "title", prev) } }, OnSettled: func(_ int, _ error, _ string, ctx wind.MutationContext) { wind.InvalidateQueriesOf(ctx.Client, func(k TaskListKey) bool { return k.Filter == "open" }) },})Each option receives its own rollback value. Returning an error from OnMutate skips the request and calls OnError, then OnSettled, for each option through the one that failed. A failed request (including a recovered panic) passes the zero result to OnSettled.
Use client.InvalidateQueriesWhere(func(k any) bool { return k == "title" }) for an untyped predicate. CancelQueriesWhere and CancelQueriesOf select in-flight work the same way. Predicates can read the cache: they run on a snapshot of keys, outside the client lock.
Work with the cache outside render
Section titled “Work with the cache outside render”wind.SetQueryData(client, "total", 3)wind.UpdateQueryData(client, "total", func(prev int, exists bool) int { return prev + 1})n, found := wind.GetQueryData[string, int](client, "total")A read miss doesn’t create an entry. The updater runs under the entry lock: return the new value instead of calling back into the same entry. Use client.CancelQueries(key) to stop matching in-flight reads or streams without destroying the client. client.Close() cancels work, clears the cache, and drains it; use it at shutdown, not on every render.
To inspect active entries, register winddt.Register(insp, client) from extras/wind/winddt with the DevTools inspector. Try async loading in the Task Manager tutorial →