My URL currently looks as following.
http://localhost:3000/path/label?default=1111
I want to append additional query string values. Thus after appending, I am expecting it to appear as follows.
http://localhost:3000/path/label?name=name&age=100&default=ab07
Current logic works when I look at it in the browser URL.
I see this:
http://localhost:3000/path/label?name=name&age=100&default=ab07
But when I console print it:
console.log(`router: ${JSON.stringify(router.location.search)}`)
I end up printing following:
router: "?default=1111"
It should have printed:
router: "?name=name&age=100&default=ab07"
Thought maybe the router updates fine, just some delay in print.
But that is not the case.
Once I have amended the query params. I need to push it to another url with same params.
At this stage it is still wrongly only holding the initial query params and ignoring my new params. Why?
Expected to push to:
newPath/?name=name&age=100&default=ab07
Incorrectly pushing to:
newPath?default=ab07
This is how I am appending the query and search params.
export const add = (router, data) => {
const pathname = router.location.pathname;
let updatedQuery = {
...router.location.query,
};
if (hasValue) {
const details = {
name: 'name',
'age': '100'
};
updatedQuery = {
...updatedQuery,
...details,
};
}
router.replace({
pathname,
query: updatedQuery,
search: new URLSearchParams(updatedQuery),
});
}
This is how I am pushing it to another path while still wanting to retain the same query params.
// This function is in another file.
redirectToAnotherPage = (router, data) => {
// other logic
return `/newPath/${router.location.search}`;
}
This is how I am calling both above functions.
import { withRouter } from 'react-router';
const constructAndRedirect() {
// other logic
add(router, data)
router.push(redirectToAnotherPage(router, data));
}