Skip to content

Commit 60e2309

Browse files
authored
Add ActionCable to rescript (#565) (#570)
* add ActionCable to rescript (#565) * unsubscribe from action cable when component didunmount * format rescript
1 parent 96f56bd commit 60e2309

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

client/app/bundles/comments/rescript/ReScriptShow.res

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ let reducer = (_, action: action): state => {
1515
}
1616
}
1717

18+
type subscriptionStatus =
19+
| Disconnected(ActionCable.subscription<unit>)
20+
| Connected(ActionCable.subscription<unit>)
21+
1822
@react.component
1923
let default = () => {
2024
let (state, dispatch) = React.useReducer(
@@ -32,6 +36,33 @@ let default = () => {
3236
}
3337
}
3438

39+
let subscribeToCommentsChannel = () => {
40+
ActionCable.subscribeConsumer(
41+
"CommentsChannel",
42+
{
43+
connected: () => {
44+
Js.Console.log("Connected")
45+
},
46+
received: (data: Actions.Fetch.t) => {
47+
SetComments([data])->dispatch
48+
},
49+
disconnected: () => {
50+
Js.Console.log("Disconnected")
51+
},
52+
},
53+
)
54+
}
55+
56+
React.useEffect1(_ => {
57+
let scription = subscribeToCommentsChannel()
58+
59+
Some(
60+
() => {
61+
ActionCable.unsubscribeSubscription(scription)
62+
},
63+
)
64+
}, [])
65+
3566
React.useEffect1(_ => {
3667
fetchData()->ignore
3768
None
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
type webSocket
2+
type optionalWebSocket = option<webSocket>
3+
type subscriptions
4+
type consumer = {
5+
disconnect: unit => unit,
6+
subscriptions: subscriptions,
7+
}
8+
type actionCable = {createConsumer: unit => consumer}
9+
type createConsumer
10+
type subscription<'sendData> = {
11+
consumer: consumer,
12+
send: 'sendData => unit,
13+
}
14+
type subscriprtionCallbacks<'updateData> = {
15+
connected: unit => unit,
16+
received: 'updateData => unit,
17+
disconnected: unit => unit,
18+
}
19+
20+
@val @scope("window") @return(nullable)
21+
external webSocket: option<webSocket> = "WebSocket"
22+
@val external actionCable: actionCable = "ActionCable"
23+
@send
24+
external createSubscription: (
25+
subscriptions,
26+
string,
27+
subscriprtionCallbacks<'updateData>,
28+
) => subscription<'sendData'> = "create"
29+
@send external sendData: (subscription<'sendData>, 'sendData) => unit = "send"
30+
@send external unsubscribeSubscription: subscription<'sendData'> => unit = "unsubscribe"
31+
@send external diconnectConsumer: consumer => unit = "disconnect"
32+
33+
let subscribeConsumer = (
34+
channnelName: string,
35+
subscriprtionCallbacks: subscriprtionCallbacks<'updateData>,
36+
) => {
37+
let consumer = actionCable.createConsumer()
38+
createSubscription(consumer.subscriptions, channnelName, subscriprtionCallbacks)
39+
}

0 commit comments

Comments
 (0)