getInitialProps is not running when Router.replace's "href" and "as" contains hash and query params inside "href" change.
#10900 opened on Mar 9, 2020
Description
Bug report
getInitialProps is not running when "href" and "as" contains hash and query params inside "href" change when calling Router.replace or Router.push
Bug description.
When pushing or replacing url and query params inside "href" (but not in "as") change, getInitialProps method is re-called. However, if both "href" and "as" include hash, the getInitialProps method is not re-called.
To Reproduce
Here is the minimum amount of code to reproduce:
import { useEffect } from 'react';
import Router from 'next/router';
const MyComponent = ({ query }) => {
// Test1 - this works as expected
/*
useEffect(() => {
let testCount = 0;
setInterval(() => {
const { route, asPath } = Router;
testCount += 1;
Router.replace(route + `?test=${testCount}`, asPath);
}, 1000);
}, []);
*/
// Test2 - getInitialProps is not re-called here
useEffect(() => {
let testCount = 0;
setInterval(() => {
const { route } = Router;
const asPath = window.location.pathname; // using window.location.pathname, becasuse Router.asPath includes the hash
testCount += 1;
Router.replace(route + `?test=${testCount}#hash`, asPath + '#hash');
}, 1000);
}, []);
return (
<>
<div>
{/* This should increment by 1 in every second */}
test: { query.test }
</div>
</>
);
};
MyComponent.getInitialProps = async ({ query }) => {
// This should run in every second
console.log('test', query.test);
return {
query
};
};
export default MyComponent;
- Add this code to any pages route and open it in browser
- If you enable Test1 inside MyComponent, you will see a number incrementing every second on the screen - that's because getInitialProps method is recalled due to the changes in query params inside "href" when calling Router.replace method.
- If you enable Test2 inside MyComponent (and disable Test1), you will NOT see a number incrementing every second on the screen - that's because getInitialProps method is NOT recalled inside "href" when calling Router.replace method.
Expected behavior
I am expecting getInitialProps to be re-called when query params change in "href" when calling Router.replace or Router.push and hash also exists in the url - that is because I do not want to show certain query params to the user in browser url, but I definitely want to keep the hash visible.
System information
- OS: macOS Catalina Version 10.15.3
- Browser: all
- Version of Next.js: [e.g. 6.0.2]
Additional context
I am trying to hide some query params in browser url and not show to the user + I want the hash to be visible in browser url.