SOLVED
I have a kinda stupid issue. I can't get rid of the query string,. Once I put it into the history, I can't find how to remove it.
I have a React app with navigation (Universal Router). I don't believe it is related to the library I use, but rather to a bad use of the URL and History API.
I have a list of users, and each has a number. I have an input form to enter the number. I append this as a query string in the form /users?nb=1
. This url is submitted to a resolver that searches in an array of paths. The action code corresponding to the /users
path has a function that reads if a query string is present. If yes, extract the number and push the new path /users/1
. This almost works: I push in fact /users/1?nb=1
..
Note: I can of course directly push /users/1
without a query string but this is an exercise.
What is the trick?? [EDIT]: override the key search:""
EDIT: https://codesandbox.io/s/universal-router-mobx-demo-jg3um?file=/src/NavBar.js
1- the emitting function, creates the query string
function handleSubmit(e) {
e.preventDefault();
let query = Object.fromEntries(new FormData(e.currentTarget));
const {pathname, search} = window.location
const qstring = new URLSearchParams(search);
for (const k in query){ qstring.append(k, query[k])};
history.push({ pathname, search: "?" + qstring });
}
1b - vs a "normal" link
const handleClick = (e) => {
e.preventDefault();
history.push({ pathname: e.target.pathname });
};
2- the conditional path (for the query string)
const searchString = new URLSearchParams(window.location.search);
const id = searchString.get("nb");
if (id) { return { redirect: `/users/${id}` } }
3- the resolving
const page = await router.resolve({ pathname: location.pathname });
if (page.redirect) {
return history.push({ pathname: page.redirect, search: "" });
} ^^^!
return render(<React.StrictMode>{page}</React.StrictMode>, root);
The pb is solved by adding search:"" which removes the trailing query string.
So as @Ouroborus showed, you just need to add search:''
in the returned url from the resolver to override the previous query string:
history.push({pathname: page.redirect, search:""})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.