Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement