hookagain

hookagain

Hooks

usePhoenixChannel

A hook that provides a phoenix channel.

Installation

npx shadcn@latest add https://hookagain.vercel.app/r/use-phoenix-channel.json

Usage

import { usePhoenixChannel } from "@/hooks/use-phoenix-channel"
import { usePhoenixSocket } from "@/hooks/use-phoenix-socket"
 
function Example() {
  const socket = usePhoenixSocket("ws://localhost:4000/socket")
  const channel = usePhoenixChannel(socket, "room:lobby", undefined, {
    "new_message": (payload) => {
      console.log("Received message:", payload.message)
    },
    "user_joined": (payload) => {
      console.log("User joined:", payload.username)
    }
  })
 
  if (!socket) {
    return <div>Connecting to Phoenix server...</div>
  }
 
  if (!channel) {
    return <div>Joining channel...</div>
  }
 
  const sendMessage = () => {
    channel.push("new_message", { message: "Hello, Phoenix!" })
  }
 
  return (
    <div>
      <p>Connected to Phoenix channel!</p>
      <button onClick={sendMessage}>
        Send Message
      </button>
    </div>
  )
}

On this page