Reputation: 26258
I am trying to integrate the Firebase Real Time Database in one of my project which is in react hooks and tried following code to read the data and to unsubscribe on component unmounted, but due to some reason unsubscribe is not working as expected and showing warning:
Warning: 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.
useEffect(() => {
listenMessages();
return () => messageRef.off('value', listenMessages);
}, [chatroom]); // here chat room comes from an asynchronous call
const [receivedMessages, updateReceivedMessages] = useState([]);
const listenMessages = () => {
if( chatroom !== null )
{
messageRef.child(chatroom)
.limitToLast(10)
.on('value', message => {
if (message.val() !== null)
{
let list = Object.values(message.val());
// Updating the state on every change and use this state to show messages inside render() function
updateReceivedMessages(list);
}
});
}
}
I have tried so many solutions from SO like this and from some other forums as well but nothing works for me. Some one please guide me what I am doing wrong here.
Edit: I have tested it by putting log()
on different places and what i understand is the listener
is still not removed.
Thanks in advance.
Upvotes: 0
Views: 719
Reputation: 331
Calling off()
on the location with no arguments removes all listeners at that location.
Reference: https://firebase.google.com/docs/database/web/read-and-write#detach_listeners
Upvotes: 1