Created
June 7, 2020 12:46
-
-
Save forki/e38db168e0d2aa38d3fffb215b40ae09 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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