简体   繁体   中英

How to prevent re-render when using sockets on React?

I have this problem with my code, it likes to re-render and reconnect to the server multiple times, and I'd like to have it so it'll connect when they log in, meaning that it would have to use my "useAuth()" function which uses a different context.

Is there any way to prevent the re-render so it doesn't reconnect multiple times and only connects once?

This is my code:

import React, { useEffect } from "react";
import { useAuth } from "./AuthContext";
import { io } from "socket.io-client";

const SocketContext = React.createContext({});

export const SocketProvider = ({ children }) => {
   const { isAuthenticated, user } = useAuth();
   useEffect(() => {
      if (isAuthenticated) {
         const socket = io("ws://localhost:3002", {
            reconnectionDelayMax: 10000,
            auth: {
               token: user.socketAuth,
            },
         });

         socket.on("connect_error", (err) => {
            if (err instanceof Error) {
               console.log(err.message);
               console.log(err.data);
            }
         });
      }
   }, []);
   return <SocketContext.Provider value="">{children}</SocketContext.Provider>;
};

Never mind, I fixed the issue, it was working how it was supposed to be. It was the server that wasn't accepting the connection and it just kept logging the ID of the socket and not actually letting it connect.

io.use(async (socket, next) => {
   const user = await User.findOne({ socketAuth: socket.handshake.auth.token });
   if (!user) {
      const err = new Error("Unauthorized");
      err.data = { message: "Unauthorized, please try again later." };
      next(err);
   }
   next(); // New line added to allow connection
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM