Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Why Gun.js duplicate messages in ReactJs

I'm implementing gun.js in react application.But messages are duplicated on each render, and on each update. Can someone help to figure out what's wrong with my code.

this my code .

import Gun from "gun/gun";
import { IGunChain, IGunInstance } from "gun/types";

class GunService {
public gun: IGunInstance<any> | undefined;
public messageListener:
| IGunChain<any, IGunInstance<any>, IGunInstance<any>, "messages">
| undefined;

  constructor() {
     this.gun = Gun("http://localhost:4000" + "/gun");
     this.messageListener = this.gun.get("messages");
   }

   public sendMessage(message: any) {
   this.messageListener?.set(message);
   }
 }
export const gunServices = new GunService();

then in my component : get message on each new update

   useEffect(() => {
     gunServices.messageListener?.map().on((message) => {
     setMessages((prevMessage) => [...prevMessage, message]);
   });
  }, []);

send message function

      const onSendMessage = () => {

       const message = {
       senderUsername: "John Doe",
       senderId: "Doe---id",
       receiverUsername: "John Doe",
       receiverId: "zizou_id",
       message: messageValue,
       date: Date.now().toLocaleString(),
       time: Date.now().toLocaleString(),
    };

     gunServices.sendMessage(message);
     setMessageValue("");
  };
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!