carloslfu/xstate-router

[Bug] Not unsubscribing on unmont from history

joernroeder opened this issue · 1 comments

I ran into a bug with your library which caused the state machine to "reactivate itself" even tho the parent component had unmounted before. It turned out that you're not unsubscribing from history changes here

history.listen(location => {

// unsubscribe should be returned
return history.listen ...

and

handleTransitionEvents(service, history, getRoutes(config))

// return unsubscribe in the useEffect hook for proper cleanup
return  handleTransitionEvents

I was able to fix it by using patch-package to patch xstate-router@0.4.3 for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/xstate-router/lib/index.js b/node_modules/xstate-router/lib/index.js
index e61b2f5..543380a 100755
--- a/node_modules/xstate-router/lib/index.js
+++ b/node_modules/xstate-router/lib/index.js
@@ -117,7 +117,7 @@ function useRouterMachine({ config, options = {}, initialContext = {}, history =
     const machine = createRouterMachine({ config, options, initialContext, history });
     const [state, send, service] = react_2.useMachine(machine, interpreterOptions);
     react_1.useEffect(() => {
-        handleTransitionEvents(service, history, getRoutes(config));
+        return handleTransitionEvents(service, history, getRoutes(config));
     }, []);
     return { state, send, service };
 }
@@ -143,7 +143,7 @@ function handleTransitionEvents(service, history, routes) {
             service.send({ type: exports.routerEvent, dueToStateTransition: true, route: path, service: service });
         }
     });
-    history.listen(location => {
+    return history.listen(location => {
         if (!service.initialized) {
             service.start();
         }

This issue body was partially generated by patch-package.