useIonViewWillLeave has stale state data

I’m trying to use the useIonViewWillLeave hook to cleanup event listeners. My component uses Twilio Chat so it has to fetch the chat channel before I register the events. That all works great, but when I try to cleanup the events I hit a Uncaught TypeError: Cannot read property 'off' of undefined error because the channel is undefined.

It seems like the useIonViewWillLeave doesn’t have any of the update state data and only the initial state when the component mounts. This doesn’t make much sense to me as the hook is intended for cleanup like this, but it’s the only conclusion I can come to.

Here’s some of the related code:

const [channel, setChannel] = useState();

useEffect(() => {
    const res = await chatChannel(client, sid);
    setChannel(res);
  }
}, [client, sid]);

console.log(channel) // logs channel object

useIonViewWillLeave(() => {
  console.log(channel) // undefined
  channel.off('typingStarted');
  channel.off('typingEnded');
  channel.off('messageAdded');
});

Where did you find this? I’ve never heard of it.

React lifecycle hooks documentation: https://ionicframework.com/docs/react/lifecycle#lifecycle-methods-in-functional-components

1 Like