ViewComponent::Live
This is a small add-on to the ViewComponent gem to make your components update automatically when data is changed serverside.
Renamed to ViewComponent::Live to follow naming convention of ViewComponent gem
Usage
Lets say you have a MiniBasketComponent that is renders the small basket in the top of your webshop.
Wouldn't it be nice if that just updated it self whenever a change happens to the draft order?
First lets create a small component for our mini basket.
This component requires a DraftOrder and will listen to any change to the draft order it renders.
class MiniBasketComponent < ViewComponent::Base
include ViewComponent::Live::Subscriber
listen_to :draft_order
def initialize(draft_order:)
@order = draft_order
end
def count
@order.product_count
end
def id
@order.id
end
end
Important! There is a strict naming requirement on the listen_to
part and named argument in initialize!
Then the component view.
Notice the = on the live block. It wraps the view in a div tag so we know what part of the page to update.
<%= live do %>
<b><%= count %> products in basket</b>
<% end %>
Finally we need to tell our DraftOrder to broadcast changes.
class DraftOrder < ApplicationRecord
include ViewComponent::Live::Broadcaster
end
Thats it. Now any update your draft order will be broadcast through ActionCable and your view will update in real time.
Installation
Add this line to your application's Gemfile:
gem 'view_component-live'
And then execute:
$ bundle
Add stimulus controller
$ yarn add stimulus-actionview-live, '1.0.0'
Add these 2 lines to your app/javascript/controllers/index.js
import LiveController from "stimulus-actionview-live"
application.register("live", LiveController)
Test
Running the tests requires a Redis server to have ActionCable running in a productionlike environment. This might seem like a bit overkill but this way one system test will test the entire gem.
In the test/dummy
app there is a complete example of a live updating component.
Note to self, remember to compile webpacker when making changes to dummy app assets
License
The gem is available as open source under the terms of the MIT License.
TODO
Nice to have
- install generator that does yarn add and adds lines to stimulus controllers file
- find a way to do collection updates, a component that lists many items
- could we do something for components that rely on multiple objects?
- allow the listen to method to accept a list of attributes so we only get updates to relevant things
- enable the live method to wrap component in any kind of tag