Skip to content

Instantly share code, notes, and snippets.

@hackape
Created February 26, 2021 08:09
Show Gist options
  • Save hackape/fa09fcfd9b60e3475a361ca69af362b2 to your computer and use it in GitHub Desktop.
Save hackape/fa09fcfd9b60e3475a361ca69af362b2 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const wsMachine = Machine(
{
initial: 'idle',
context: {
ws: null,
},
states: {
idle: {
on: {
CONNECT: 'connecting',
},
},
connecting: {
invoke: {
src: 'createWsInstance',
onDone: {
target: 'connected',
actions: assign({ ws: (ctx, evt) => evt.data }),
},
},
},
connected: {
activities: [''],
},
},
},
{
activities: {
handleMessages: ctx => {
const onMessage = ev => {
console.log(ev.data)
}
ctx.ws.addEventListener('message', onMessage)
return () => {
ctx.ws.removeEventListener('message', onMessage)
}
},
},
services: {
createWsInstance: (ctx, evt) => {
return new Promise((resolve, reject) => {
const ws = new WebSocket(evt.data.url)
ws.addEventListener(
'open',
ev => {
resolve(ws)
},
{ once: true }
)
})
},
},
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment