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);
}, [client, sid]);

console.log(channel) // logs channel object

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

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

React lifecycle hooks documentation:

1 Like

I just came across this very behaviour too - can anyone provide any insight into this?

Seems to be undocumented… surprise, surprise, but I noticed this as part of the typings: Screen Shot 2020-04-09 at 11.17.39 AM

Apparently these hooks accept a dependency array, so give that a shot.

1 Like

wow, you are right! it now works correctly. Thank you!

This worked perfectly, thanks! walgreenslistens