tl;dr LiveView dashboard that updates from changes in the database, triggered by PubSub
What is this?
A simple demo of Phoenix LiveView functionality for a "live dashboard". When "items" in the database are changed, the dashboard updates without reloading the page.
Below we have the standard phx.gen.html scaffold on the left, and a LiveView on the right.
As we create, modify or delete the items, they are updated automagically in the LiveView.
How can I try it out?
- Clone the repo
- Install dependencies with
mix deps.get
- Create and migrate your database with
mix ecto.setup
- Install Node.js dependencies with
cd assets && npm install
- Start Phoenix endpoint with
mix phx.server
Visit localhost:4000
from your browser for the live view, and /items for the items crud scaffold.
How does it work?
-
Once LiveView is setup in your project (docs, tutorial), you can define a module to
use LiveView
, and then implementrender/1
,mount/2
, andhandle_event/3
functions to control your live view. -
In this specific example, the
render
function just renders the simple live template. Themount
function retrieves the items from the database and then subscribes to the PubSub topic. The 2handle_event
functions are used from the live view when creating or updating an item. Thehandle_info
function re-fetches the database items to supply them to the live view. -
When items are updated in the database using the
Items
context, we call PubSub.broadcast on the same topic which notifies the live view to update.