Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io not removing listener from every react component

i want to make off method from socket.io client to remove all match running listeners from all react components Because currently i'm listening to a same event on two different component , both are in componentDidMount,

Board.js

 socket.on('achievement', (data) => {
                const updateAchievement= [data, ...this.state.getAchievements];
                this.setState({
                    recentAchievements: this.state.recentAchievements.concat(data),
                    getAchievements: updateAchievement
                });
            });

Dashboard.js

 socket.on('achievement', (data) => {
                const updateAchievement= [data, ...this.state.getAchievements];
                this.setState({
                    recentAchievements: this.state.recentAchievements.concat(data),
                    getAchievements: updateAchievement
                });
            });

Currently if the end-user turn off listening to the event while on DashBoard.js , the Board.js is still actively receiving data which i don't want. The board.js component is always on the view that's why i can see the data still coming.

How i unsubscribe

DashBoard.js

componentWillUnmount(){
            socket.off("achievement");
     }

Like i said above, the Board component is always in the view and i can still see data coming in.

How can i stop this?

like image 960
JEEZSUSCRIZE Avatar asked Aug 26 '18 12:08

JEEZSUSCRIZE


Video Answer


1 Answers

Just use the componentWillUnmout() lifecycle method to call socket.off() with the handler. Note that off() requires the previously subscribed handler to be passed as the second argument:

class MyComponent extends Component {
    updateAchievement = data => {
        this.setState(prevState => ({
                    recentAchievements: [...prevState.recentAchievements, data],
                    getAchievements: [data, ...prevState.getAchievements]
        }));
    }

    componentDidMount() {
       socket.on('achievement', this.updateAchievement);
    }

    componentWillUnmount() {
       socket.off('achievement', this.updateAchievement);
    }

    // ...
}

Note that you should not use this.state when updating the state. Always use the version of setState that takes a function where the first argument is the previous state and update based on that.

like image 52
trixn Avatar answered Sep 17 '22 00:09

trixn