Skip to content

Instantly share code, notes, and snippets.

@forki
Created June 7, 2020 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forki/e38db168e0d2aa38d3fffb215b40ae09 to your computer and use it in GitHub Desktop.
Save forki/e38db168e0d2aa38d3fffb215b40ae09 to your computer and use it in GitHub Desktop.
FunctionComponent.Of(fun (props: {| url : string; retryTimeSpan : TimeSpan; onMessage: 'Data -> unit |}) ->
let connected = Hooks.useState(false)
let wasClosed = Hooks.useState(false)
let register() =
printfn "Trying to connect"
let ws = create props.url
ws.onclose <- unbox (fun _ ->
match ws.readyState with
| WebSocketState.CLOSED ->
printfn "CLOSED!!"
connected.update(fun _ -> true)
| _ -> ()
)
ws.onmessage <- unbox (fun (msg: MessageEvent) ->
let msg' = msg.data |> string
if not (System.String.IsNullOrWhiteSpace msg') then
printfn "NEW MESSAGE: %s" msg'
let decoded = ServerCode.JSON.ofJson<'Data> msg'
props.onMessage decoded
unbox None
)
ws.onopen <- unbox (fun _ ->
match ws.readyState with
| WebSocketState.OPEN ->
printfn "Connected!!"
connected.update(fun _ -> true)
| _ -> ()
)
{ new IDisposable with
member __.Dispose() =
wasClosed.update(fun _ -> true)
printfn "CLOSING!!"
ws.close() }
Hooks.useEffectDisposable(register,[||])
nothing
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment