LiveStores make it easy to update Svelte stores in real-time through ActionCable.
In this example we take a look at how to display user notifications in real-time.
First, create a channel that will be used to send notifications:
# user_channel.rb
class UserChannel < ApplicationCable::Channel
def subscribed
stream_for current_user
end
end
Inside your component, set up a subscription and initialize a notifications
store.
<script>
// some_component.svelte
import { subscribe, getStore } from 'livestores'
import { onDestroy } from 'svelte'
// Set up a subscription to the UserChannel
const channel = subscribe('UserChannel')
// Don't forget to unsubscribe when the component is destroyed
onDestroy(channel.unsubscribe)
// Get a reference to the notifications store and initialize it with an empty array
const notifications = getStore('notifications', [])
$: console.log($notifications)
</script>
Now you can server-side push directly into the notifications
store through the UserChannel:
UserChannel[some_user].store('notifications').append({text: "Hello from Ruby"})
Under construction
Add this line to your application's Gemfile:
gem 'livestores'
And then execute:
$ bundle install
Install the package:
$ npm i -D livestores