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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With