Sử dụng broadcast reverb với nextjs
Việc liên quan đến kết nối giữa nextjs và laravel :
Trong nextjs :
lib/echo.tsx
import Echo from "laravel-echo";
import Pusher from "pusher-js";
let echo: Echo | null = null;
if (typeof window !== "undefined") {
(window as any).Pusher = Pusher;
echo = new Echo({
broadcaster: "reverb",
key: process.env.NEXT_PUBLIC_REVERB_APP_KEY!,
wsHost: process.env.NEXT_PUBLIC_REVERB_HOST!,
wsPort: 443,
wssPort: 443,
forceTLS: true,
enabledTransports: ["ws", "wss"],
authEndpoint: process.env.NEXT_PUBLIC_API_URL + "/broadcasting/auth",
auth: {
headers: {
Authorization: `Bearer 123435345436546`,
Accept: "application/json",
},
},
});
}
export default echo;
Trong page.tsx
"use client";
import Image from "next/image";
import { useEffect, useState } from "react";
import echo from "@/lib/echo";
import axios from "axios";
export default function Home() {
interface Comment {
id?: number;
body?: string;
}
const [thongtin, setThongtin] = useState<Comment[]>([]);
useEffect(() => {
const channel = echo.channel("post.1");
channel.listen(".comment.created", (event: any) => {
console.log("Nhận được:", event);
console.log(event.id);
console.log(event.body);
setThongtin((prev) => [
{
id: event.id,
body: event.body,
},
...prev,
]);
});
return () => {
echo.leaveChannel("post.1");
};
}, []);
useEffect(() => {
async function fetchData() {
const response = await axios.get("https://dummyjson.com/comments/post/1");
console.log(response.data.comments);
setThongtin(response.data.comments);
}
fetchData();
}, []);
return (
<>
xin chào
{thongtin.map((item) => (
<div key={item.id}>
{item.id} - {item.body}
</div>
))}
</>
);
}
Trong .env
NEXT_PUBLIC_REVERB_APP_KEY='f3shmi3kvipmwv8cd5r8'
NEXT_PUBLIC_REVERB_HOST='reverb.kiemtruyen.online'
NEXT_PUBLIC_REVERB_PORT=443
Link download : https://drive.google.com/file/d/1vpmDyeeBXuZ6b1W992aTeMsXYodamhUp/view?usp=sharing
Trong laravel :
<?php
namespace App\Events\Broadcast;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PostCreateBroadcast implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*/
public function __construct(public $data)
{
}
/**
* Get the channels the event should broadcast on.
*
* @return array<int, Channel>
*/
public function broadcastOn(): array
{
return [
new Channel('post.1'),
];
}
public function broadcastWith(): array
{
return [
'id' => $this->data['id'],
'body' => $this->data['body'],
];
}
public function broadcastAs(): string
{
return 'comment.created';
}
}