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

Create a useStateLazy method which takes a callback #277

Merged
merged 2 commits into from
Mar 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/Avalonia.FuncUI/Components/Context/Context.fs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,25 @@ type IComponentContext =
/// <param name="renderOnChange">re-render component on change (default: true).</param>
abstract useState<'value> : initialValue: 'value * ?renderOnChange: bool -> IWritable<'value>

/// <summary>
/// Attaches a value from a function to the component context.
/// <example>
/// <code>
/// Component (fun ctx ->
/// (* expensive operation that should only happen once on initialisation *)
/// let count = ctx.useStateLazy (fun () -> Math.Sqrt(42))
/// ..
/// // id will have the same value during the whole component lifetime. (unless changed via 'id.Set ..')
/// let id = ctx.useState ((fun () -> Guid.NewGuid()), renderOnChange=false)
/// ..
/// )
/// </code>
/// </example>
/// </summary>
/// <param name="buildInitialValue">function will be called once during the component lifetime.</param>
/// <param name="renderOnChange">re-render component on change (default: true).</param>
abstract useStateLazy<'value> : buildInitialValue: (unit -> 'value) * ?renderOnChange: bool -> IWritable<'value>

/// <summary>
/// Attaches a passed <c>IWritable&lt;'value&gt;</c> value to the component context.
/// <example>
Expand Down Expand Up @@ -317,6 +336,16 @@ type Context (componentControl: Avalonia.Controls.Border) =
)
) :?> IWritable<'value>

member this.useStateLazy(buildInitialValue: unit -> 'value, ?renderOnChange: bool) =
this.useStateHook<'value>(
StateHook.Create (
identity = callingIndex,
state = StateHookValue.Lazy (fun _ -> new State<'value>(buildInitialValue()) :> IAnyReadable),
renderOnChange = defaultArg renderOnChange true
)
) :?> IWritable<'value>


member this.control = componentControl

interface IDisposable with
Expand Down