React useNavigate() not triggering window.addEventListener('locationchange' / history

49 Views Asked by At

I have two parts of a React App -

One part is using useNavigate() to change the hashroute - ie app/pageOne to app/PageTwo

I have another part of the App but it is not react code, that is trying to monitor page changes and do a console.log.

I have tried everything I can think of to listen to the browser and detect the page change but none of the logging is being triggered when using useNavigate() but it is when the browser back button is used.

Test code to listen to the browser

const browserHistory = createBrowserHistory({ basename: '' });
const browserHistory2 = createHashHistory({ basename: '' });

browserHistory.listen(() => {
    console.log('standard');   
});
browserHistory2.listen(() => {
    console.log('hash');
    }
});

window.addEventListener('locationchange', function () {
    console.log('location changed!');
});

window.addEventListener('hashchange', function () {
    console.log('location hash changed!');
});

window.addEventListener('popstate', function() { 
    console.log('location pop changed!');  
  });

Other people have solved this using the React useLocation hook but I can't as my monitoring code is not React.

this code is already using the history package that should make this easy - https://github.com/remix-run/history/blob/3e9dab413f4eda8d6bce565388c5ddb7aeff9f7e/docs/getting-started.md

0

There are 0 best solutions below