-
Notifications
You must be signed in to change notification settings - Fork 44
Description
When I was first trying to figure out Bonsai, I drew a lot of parallels to React paired with the Recoil state management library. Recoil adds an orthogonal computation DAG, rooted in shared elements of state called "atoms", which can be consumed by React components. Changes to atoms propogate down the computation graph and selectively trigger React components to re-render.
If the understanding I've come to have through this discussion is accurate, it seems that in Bonsai, the equivalent to atoms is:
Bonsai.Var, for truly global state, since it acts as a mutable container that can feed into computations viaBonsai.Var.value.Bonsai.Dynamic_scope, for "semi-global" state which is shared among some computation subgraph.
Is this an idiomatic way of thinking about Bonsai and global state?
As an example of something I'm unsure about, I recently had to build a primitive router/link/url system, where components that depended on the current URL (e.g. fetching a query depending on a path argument) would incrementally recompute as the URL changed. A tl;dr of my implementation:
open Bonsai_web
open Bonsai.Let_syntax
let get_uri () =
let open Js_of_ocaml in
Dom_html.window##.location##.href |> Js.to_string |> Uri.of_string
(* This creation of a "global" variable feels like it might be an anti-pattern *)
let uri_atom = Bonsai.Var.create (get_uri ())
let set_uri uri =
let open Js_of_ocaml in
let str_uri = Js.string (Uri.to_string uri) in
Dom_html.window##.history##pushState Js.null str_uri (Js.Opt.return str_uri);
Bonsai.Var.set uri_atom uri
let curr_path_novalue () = uri_atom |> Bonsai.Var.get |> Uri.path
let curr_path = Bonsai.Var.value uri_atom |> Value.map ~f:Uri.path_and_query
let link_vdom ?(attrs = []) ?(children = Vdom.Node.none) uri =
let set_uri = Effect.of_sync_fun (fun new_uri -> set_uri new_uri) in
let link_attrs =
[
Vdom.Attr.href (Uri.to_string uri);
Vdom.Attr.on_click (fun e ->
Js_of_ocaml.Dom.preventDefault e;
set_uri uri);
]
in
Vdom.Node.a ~attr:(Vdom.Attr.many (attrs @ link_attrs)) [ children ]
let router routes =
let uri = Bonsai.Var.value uri_atom in
let path = Value.map uri ~f:Uri.path in
routes pathThere's a lot to be improved (e.g. functorizing over a fixed variant of routes), but one of the things I noticed is that my approach has a single global Var.t, whereas the "Bonsai web ui url var" implementation provides functions to create separate instances of url vars. Wouldn't the latter approach mean that changes to one url var instance wouldn't propogate to other instances?