...

/

Update a Client with Real-time Data

Update a Client with Real-time Data

Learn how to send real-time data to a client.

We'll cover the following...

Real-time data

Instead of using a Channel broadcast to replace content by swapping out the HTML and sending the client server-rendered HTML, our real-time message will include details about the new stock level in this lesson. The JavaScript client will use this data to change the relevant parts of the DOM to affect the view. Our message stock_change will include the product ID, item ID, and the new stock level.

Our ProductChannel will be modified to define the new broadcast function. This function will broadcast if the stock level changed, or skip the broadcast if it’s identical. This prevents unnecessary data from being sent to connected clients.

Add the stock level change function to the ProductChannel module.

Press + to interact
# sneakers_23/lib/sneakers_23_web/channels/product_channel.ex
def notify_item_stock_change(
previous_item: %{available_count: old},
current_item: %{available_count: new, id: id, product_id: p_id}
) do
case {
ProductView.availability_to_level(old),
ProductView.availability_to_level(new)
} do
{same, same} when same != "out" ->
{:ok, :no_change}
{_, new_level} ->
Endpoint.broadcast!("product:#{p_id}", "stock_change", %{
product_id: p_id,
item_id: id,
level: new_level
})
{:ok, :broadcast}
end
end

A case statement is used on line 6 to prevent duplicate updates from being sent to a client. There ...