B
B
Breezy
Search…
Chat App

Short-polling

Say you have a list of chat messages that you want to periodically update. Here's a simple way to do that with a simple setTimeout:
1
componentDidMount() {
2
this.polling = setInterval(() => {
3
this.props.remote('/messages?bzq=data.messages')
4
})
5
}
Copied!
And corresponding messages/index.json.props
1
json.data(search: params['bzq'])
2
json.header do
3
...
4
end
5
6
json.messages do
7
json.array! @messages do |msg|
8
json.body msg.body
9
end
10
end
11
end
Copied!

Long-polling

You can use a combination of Rails renderers, ActionCable, PropsTemplate fragments, and preloading to stream updates to your users without much effort.
For example, if you already have an ActionCable channel setup, simply render the props and send the rendered node over the wire:
1
# index.json.props
2
3
json.data(search: params[:bzq]) do
4
json.posts do
5
json.array! @posts, partial: ['post', fragment: true] do
6
end
7
end
8
end
Copied!
Render and broadcast via a background job:
1
renderer = PostsController.renderer.new(
2
"action_dispatch.request.parameters"=>{bzq: 'data.posts.0'},
3
"action_dispatch.request.formats"=>[Mime[:json]]
4
)
5
6
message = renderer.render(:index)
7
8
ActionCable.server.broadcast('web_notifications_channel', message: message)
Copied!
Receive the JSON on the client-side and dispatch it to your reducer:
1
window.App.cable.subscriptions.create("WebNotificationsChannel", {
2
received: function({message}) {
3
const response = JSON.parse(message)
4
5
this.props.dispatch({
6
type: "UPDATE_POST_FOOBAR",
7
payload: response.data
8
})
9
}
10
})
Copied!
Last modified 3mo ago
Copy link