Skip to content

Commit

Permalink
Add ActionCable to rescript (#565) (#570)
Browse files Browse the repository at this point in the history
* add ActionCable to rescript (#565)

* unsubscribe from action cable when component didunmount

* format rescript
  • Loading branch information
Yassa-hue authored Nov 23, 2023
1 parent 96f56bd commit 60e2309
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
31 changes: 31 additions & 0 deletions client/app/bundles/comments/rescript/ReScriptShow.res
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ let reducer = (_, action: action): state => {
}
}

type subscriptionStatus =
| Disconnected(ActionCable.subscription<unit>)
| Connected(ActionCable.subscription<unit>)

@react.component
let default = () => {
let (state, dispatch) = React.useReducer(
Expand All @@ -32,6 +36,33 @@ let default = () => {
}
}

let subscribeToCommentsChannel = () => {
ActionCable.subscribeConsumer(
"CommentsChannel",
{
connected: () => {
Js.Console.log("Connected")
},
received: (data: Actions.Fetch.t) => {
SetComments([data])->dispatch
},
disconnected: () => {
Js.Console.log("Disconnected")
},
},
)
}

React.useEffect1(_ => {
let scription = subscribeToCommentsChannel()

Some(
() => {
ActionCable.unsubscribeSubscription(scription)
},
)
}, [])

React.useEffect1(_ => {
fetchData()->ignore
None
Expand Down
39 changes: 39 additions & 0 deletions client/app/bundles/comments/rescript/bindings/ActionCable.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
type webSocket
type optionalWebSocket = option<webSocket>
type subscriptions
type consumer = {
disconnect: unit => unit,
subscriptions: subscriptions,
}
type actionCable = {createConsumer: unit => consumer}
type createConsumer
type subscription<'sendData> = {
consumer: consumer,
send: 'sendData => unit,
}
type subscriprtionCallbacks<'updateData> = {
connected: unit => unit,
received: 'updateData => unit,
disconnected: unit => unit,
}

@val @scope("window") @return(nullable)
external webSocket: option<webSocket> = "WebSocket"
@val external actionCable: actionCable = "ActionCable"
@send
external createSubscription: (
subscriptions,
string,
subscriprtionCallbacks<'updateData>,
) => subscription<'sendData'> = "create"
@send external sendData: (subscription<'sendData>, 'sendData) => unit = "send"
@send external unsubscribeSubscription: subscription<'sendData'> => unit = "unsubscribe"
@send external diconnectConsumer: consumer => unit = "disconnect"

let subscribeConsumer = (
channnelName: string,
subscriprtionCallbacks: subscriprtionCallbacks<'updateData>,
) => {
let consumer = actionCable.createConsumer()
createSubscription(consumer.subscriptions, channnelName, subscriprtionCallbacks)
}

0 comments on commit 60e2309

Please sign in to comment.