Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

javascript - Socket in react is not listening for the second time

I'm very new to socket and trying to integrate socket in react and node.js simple CRUD application. My backend always emits the event and Frontend listens to the event. Below is the scenario

I'm deleting an item from the list and for which I'm emitting an event from Backend after the record is removed and I'm listening for the same event in react in useEffect but the socket stops listening from second time onwards. I even did socket.off in unmount for that event but still no luck.

PFB Node.js code

export async function deleteSection(req: Request, res: Response, next: NextFunction): Promise<any> {
  try {
    await findNotesBySectionAndDelete(req.params.id);
    const deleted = await Section.findByIdAndRemove(req.params.id);
    if (!deleted) {
      res.status(500).json({ message: `Cannot delete resource`});
      return next(deleted);
    }
    socket.emit("delete-section", deleted); // this is where I'm emitting the event when deleting an item
    return res.status(200).send(deleted);
  } catch(err) {
    return res.status(500).send(err || err.message);
  }
}

PFB React code:

const [selectedSection, setSelectedSection] = useState<{[Key: string]: any}>({});

useEffect(() => {
    /* Delete section  */
    // this is not listening again from second time onwards when I delete another item
    socket.on("delete-section", (deletedSection: {[Key:string]: any}) => {
        if(!deletedSection){
            return;
        }
        filterSections(deletedSection?._id)
    });
    return () => {
        socket.off("delete-section");
    };
}, [socket, selectedSection]);


const filterSections = (sectionId: string) => {
    if(!sections){
        return;
    }
    if(sectionId === selectedSection?._id){
        const filteredSections: Array<{[Key: string]: any}> = sections.filter(
            item => item._id !== sectionId,
        )
        setSections(filteredSections);
        setSelectedSection({});
    }
}

Why is it not listening from second time onwards?

question from:https://stackoverflow.com/questions/66059646/socket-in-react-is-not-listening-for-the-second-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I solved it with help of my friend. The issue that I was closing the socket connection in one of the child component and that was causing the issue. In my case I shouldn’t close connection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...