1

I use Next.js on my project and I need to make a dynamic query string. I use this code:

const createQuery = (filter) => {
  let currentPath = router.pathname;
  let filterSize = Object.keys(filter).length;

  filterSize != 0 ? (currentPath += "?") : null;

  Object.keys(filter).map(function (key, index) {
    currentPath +=
      key + "=" + filter[key] + (index === filterSize - 1 ? "" : "&");
  });

  router.push(currentPath);
};

It works but I don't send an array to query string. How can I do this? Also, ss there an easier way to create a query string in Next.js?

2 Answers 2

2

You can easily pass dynamic query strings using nextjs/router

Router.push accepts query as an object which will be converted to query parameters.

for example:

 Router.push({
  pathname: currentPath,
  query: {
     page: 1,
     skip: 10
  }
})
// results into currentPath?page=1&skip=10
Sign up to request clarification or add additional context in comments.

Comments

1

You can use URLSearchParams to simplify your code

const params = new URLSearchParams({
  var1: "value",
  var2: "value2",
  arr: "foo",
});
console.log(params.toString());
//Prints "var1=value&var2=value2&arr=foo"

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.