Ad

How To Cancel Socket.io-client Subscription In React

I have an app in TypeScript React that uses socket.io client. The codes look like this:

import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';

const MyComponent = () => {

        const socket = io(WS_URL);

        const [ info, setInfo ] =  useState<string[]>([]);

        useEffect(() => {

                socket.open();

                socket.emit('get_info');

                socket.on('ws_reply', (msg:any) => {
                        setInfo(prevData => [...prevData, msg['data']]);
                }

                return(() => {socket.close()));

        }, []);

        return(
                <div>
                        {info}
                <div/>
        );

}

export { MyComponent };

When I run the site, the error below appeared at the second attempt when I visit the site (e.g. I when to another page of my application and then press back to this page). I have close the socket.io connection as above. But the error still seems to appear:

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Ad

Answer

I would try adding const socket = io(WS_URL) snippet into useEffect() instead.

See as the following:

const [ info, setInfo ] =  useState<string[]>([]);

useEffect(() => {
    const socket = io(WS_URL);

    socket.open();
    socket.emit('get_info');
    socket.on('ws_reply', (msg:any) => {
       setInfo(prevData => [...prevData, msg['data']]);
    }

    return(() => {socket.close()));
}, []);

See this example: Socket.IO, React and Node.js: implementing the React client

I hope this helps!

Ad
source: stackoverflow.com
Ad