Roman Karpyshyn
Roman Karpyshyn

Reputation: 199

socket starts a connection in other component

I have an incomprehensible problem. I have 2 React components Signin and Chat, connection to the socket should only occur in second component Chat.

    const url = 'http://localhost:4000';
    const socket = openSocket(url);

    const Chat = () => {

      useEffect(() => {
        subscribeToChanges();
      }, []);

    const subscribeToChanges = () => {
    socket.on('getAllMessages', message => {
      const {userMessage, userId} = message;
      setState(prevState => ({
        ...state,
        messages: [...prevState.messages, {userMessage, userId}]
      }));
    });
  };
     return (
        <div>
        </div>
      );
    };

    export default Chat;

But when I update both components in the browser, I see at my backend logs and they show the same connection to the socket in both. But as I understand it, this should happen only when i update a `Chat

Maybe this is somehow influenced by the routes, or i don't understand sockets enough

    <Switch>
      <Route exact path="/">
        <SignIn/>
      </Route>
     <Route exact path="/chat">
       <Chat/>
     </Route>
   </Switch>

Upvotes: 0

Views: 320

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281656

You must create your socket instance inside of the component and not in the file otherwise the instance will created when you import the file and not when you render it

Also you must clean ip your socket instance when you unmount the component

 const url = 'http://localhost:4000';
 const Chat = () => {
      const socket = useRef(null);
      useEffect(() => {

        socket.current = openSocket(url); // create socket here and pass it on
        subscribeToChanges();
        return () => {
             // close socket on unmount
             socket.current.close();
        }
      }, []);

  const subscribeToChanges = () => {
    socket.current.on('getAllMessages', message => {
      const {userMessage, userId} = message;
      setState(prevState => ({
        ...state,
        messages: [...prevState.messages, {userMessage, userId}]
      }));
    });
  };
     return (
        <div>
        </div>
      );
    };

    export default Chat;

Upvotes: 3

Related Questions