4

I have a component that needs to copy all of the query parameters from the URL. However I do not want to copy dynamic route parameters. So if it is used in a component like: /pages/model/{modelId}.tsx and the url is /model/123456?page=2&sort=column&column=value, I would like to retrieve the following object:

{
  page: 2,
  sort: "column",
  column: "value"
}

I would use useRouter().query but this would include modelId. And the router object doesn't seem to have any other list of parameters.

So how would I distinguish regular URL parameters from dynamic route parameters?

2 Answers 2

3

Why not use the built-in URL API instead:

const url = new URL(window.location.href);

url.searchParams.get("page"); // a string or null if not present

Going a little further, you could also wrap this in a hook for future use.

If you want the search parameters as an object, you could wrap it in Object.fromEntries too:

const params = Object.fromEntries(new URL(window.location.href).searchParams);

params.page; // string or undefined now
Sign up to request clarification or add additional context in comments.

1 Comment

I think I wasn't clear in my wording so I updated the question. Your answer is still very useful, but I will actually use something like Object.fromEntries(new URL(window.location.href).searchParams) in my project. If you would update your answer I would like to give you the point.
0

In my case I stripped the unwanted key from the query object. In this case the dynamic url param.

I used lodash for this, but this could be perfectly done with Javascript only.

export const ignoreQueryParam = (obj, key) => _.omit(obj, key);

Applied to your case:

const router = useRouter();
const searchQuery = ignoreQueryParam(router.query, 'modelId');

I hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.