Skip to content

Instantly share code, notes, and snippets.

@forki

forki/socket.fs

Created Jun 7, 2020
Embed
What would you like to do?
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