...

/

Render Real-time HTML with Channels (Front-end)

Render Real-time HTML with Channels (Front-end)

Learn how to connect our frontend using channels.

We'll cover the following...

Rendering HTML

Now that our back end is configured, let’s connect our front end using the Phoenix Channel JavaScript client. Our strategy will be to grab the data-product-id attributes from our HTML DOM elements and then connect to a Channel per matching product ID.

Press + to interact
// sneakers_23/assets/js/app.js
import css from "../css/app.css"
import { productSocket } from "./socket"
import dom from './dom'
const productIds = dom.getProductIds()
if (productIds.length > 0) {
productSocket.connect()
productIds.forEach((id) => setupProductChannel(productSocket, id))
}
function setupProductChannel(socket, productId) {
const productChannel = socket.channel(`product:${productId}`)
productChannel.join()
.receive("error", () => {
console.error("Channel join failed")
})

This isn’t a runnable example because we need to define our dom.js and socket.js files. However, the flow that we’ll follow is complete. We’ll soon add additional setup operations into setupProductChannel/1, which is why that function ends without closing.

Press + to interact
// sneakers_23/assets/js/socket.js
import { Socket } from "phoenix"
export const productSocket = new Socket("/product_socket")

This file makes the productSocket available for import. It’s a good idea to keep the code separated with exported modules to help increase the focus of a particular file, even if there’s no logic in the file now. It also gives us a ...