amark / gun

An open source cybersecurity protocol for syncing decentralized graph data.
https://gun.eco/docs
Other
18.03k stars 1.16k forks source link

Gun.js duplicates messages in React #1255

Closed Jonath-z closed 2 years ago

Jonath-z commented 2 years ago

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("");
  };
Jonath-z commented 2 years ago

On each page render messages are duplicated

can someone who already face this issue , help me !

draeder commented 2 years ago

What was the solution? Please note it in a comment so if others run into this they can solve it.