Pusher making multiple channel every few seconds

23 Views Asked by At

I am new to web socket and I was just trying pusher out.I was making a realtime comment section,here is my code

"use client";
import { useState, useEffect } from "react";
import Pusher from "pusher-js";

export default function Home() {
  const [comment, setComment] = useState("");
  const [realCommentArray, setRealCommentArray] = useState([]);

  Pusher.logToConsole = true;

  const pusher = new Pusher(PUSHER_KEY, {
    cluster: "ap2",
  });

  const channel = pusher.subscribe("chat");
  channel.bind("my-event", function (data) {
    setRealCommentArray((oldArray) => [...oldArray, data.comment]);
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await fetch("api/pusher", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ comment: comment }),
      });
      console.log(response);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div>
      <form>
        <input
          type="text"
          placeholder="Comment"
          onChange={(e) => {
            setComment(e.target.value);
          }}
        ></input>
        <button type="submit" className="bg-red-800" onClick={handleSubmit}>
          Submit
        </button>
      </form>
      {realCommentArray.map((item) => {
        return <div>{item}</div>;
      })}
    </div>
  );
}

I dont know why but pusher is making unnecessary calls hence pushing the same comment multiple times

Why is this happening?Is its beacause of the state hook that I am using?

0

There are 0 best solutions below