Skip to content

Instantly share code, notes, and snippets.

@MarcelCutts
Created September 18, 2017 23:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarcelCutts/20cbc9326a0914f4557c0413597c42b4 to your computer and use it in GitHub Desktop.
Save MarcelCutts/20cbc9326a0914f4557c0413597c42b4 to your computer and use it in GitHub Desktop.
A super hacky attempt to get async fetching working on button press.
open Bs_fetch;
let sj json :list string => Json.Decode.(json |> list string);
type remoteData 'e 'a =
| NotAsked
| Loading
| Failure 'e
| Success 'a;
let se = ReasonReact.stringToElement;
type state = {data: remoteData string (list string)};
let component = ReasonReact.reducerComponent "Tubes";
let displayData data =>
ReasonReact.arrayToElement (Array.of_list (List.map (fun i => <div> (se i) </div>) data));
let make _children => {
...component,
initialState: fun () => {data: NotAsked},
reducer: fun action _state =>
switch action {
| NotAsked => ReasonReact.NoUpdate
| Loading => ReasonReact.Update {data: Loading}
| Failure msg => ReasonReact.Update {data: Failure msg}
| Success data => ReasonReact.Update {data: Success data}
},
render: fun {state, reduce} =>
<div>
(
switch state.data {
| NotAsked =>
<div>
(se "Not yet asked")
<button
onClick=(
fun _ =>
Js.Promise.(
fetch "http://localhost:3004/test" |> then_ Response.json |>
then_ (fun r => reduce (fun _ => Success (sj r)) |> resolve)
) |> ignore
)>
(se "Fetch some data")
</button>
<button onClick=(reduce (fun _ => Failure "boom"))> (se "\159\148�") </button>
</div>
| Loading => <div> (se "loading") </div>
| Failure msg => <div> (se msg) </div>
| Success data => <div> (displayData data) </div>
}
)
</div>
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment