Obtain the non-dynamic route parameters as query parameters in Next.js

I need help figuring out how to extract specific query parameters from a URL in my component. I want to exclude dynamic route parameters, such as {modelId}. For example, if the URL is

/model/123456?page=2&sort=column&column=value
, I only want to retrieve the following object:

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

Using useRouter().query includes all parameters, including modelId. The router object does not seem to provide a way to differentiate between regular and dynamic route parameters.

Can anyone suggest how I can identify regular URL parameters while excluding dynamic ones?

Answer №1

Have you considered utilizing the native URL API instead?

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

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

To take it a step further, you could encapsulate this in a custom hook for later use.

If you prefer the search parameters as an object, you can also utilize Object.fromEntries:

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

params.page; // now returns a string or undefined

Answer №2

In my particular situation, I removed the unnecessary key from the query object, which in this instance was the dynamic URL parameter.

Although I utilized lodash for this task, it can also be achieved using plain JavaScript.

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

If you apply this to your own scenario:

const route = useRouter();
const updatedQuery = eliminateQueryParameter(route.query, 'modelId');

I trust that this information proves beneficial to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Nodejs cookie settings

I am currently working on a small petition project and I want to implement a feature where a user who signs the petition will have a cookie set so that when they try to access the page again, they are redirected to a "thanks page". If the user has not sign ...

Having trouble making .click() function work in jQuery

Struggling with translating my javascript code to jQuery for homework. The .click function is causing me some serious issues. Here's a snippet of the code I'm working on: (document).ready(function() { $("start_test").click (function() { ...

What crucial element is absent from my array.map function?

I have successfully implemented a table with v-for in my code (snippet provided). However, I am now trying to use Array.map to map one array to another. My goal is to display colors instead of numbers in the first column labeled as networkTeam.source. I at ...

Is there a way to fetch and display property changes in Vue Material's md-dialog?

In the component hierarchy, there is a parent component containing a child, which further contains an md-dialog component. The dialog is opened from the parent component using the following code: ParentComponent.vue <template> <div> < ...

I'm attempting to utilize AJAX to modify the sorting and ordering arguments in a WP_Query, yet I'm struggling to pinpoint the reason behind the failure of my code

After hours of non-stop work, about 6 solid hours with no breaks, I am baffled as to why this code isn't working. Let's take a look at the form in question: <div id="wp-ajax-filter-search" class="full"> <form ...

Exploring the intricacies of Node-Craigslist syntax

Greetings! I am currently utilizing the node-craigslist package found at https://github.com/brozeph/node-craigslist and I am in need of assistance with some syntax related to the details method. The documentation provides the following example: client . ...

Guide on displaying link parameter information on a separate webpage using only JavaScript

While doing some research, I came across an issue. I have a page called specifications.html with three links: details.html?id=1, details.html?id=2, and details.html?id=3. My goal is to display the details of each link when someone clicks on it. For examp ...

Refresh cloned element after making changes to the original element

Just starting to explore Jquery and looking for some guidance to get me started :) Question: I'm facing an issue with a cart total price that is displayed in a different part of the page using clone(). I want this cloned price to automatically update ...

Checking JSON formatted actions in Rails 4: A guide to testing

I'm in the process of testing a Rails application where all my actions return data formatted in json. An example of this is within the UsersController # POST /users.json def create @user = User.new(user_params) respond_to do |format| ...

Comparing NextJs hydration with using the client-side approach

Currently exploring the ins and outs of NextJs to grasp its fundamental features. It is my understanding that by default, NextJs components operate on the server-side and utilize Hydration to enable interactivity shortly after displaying pre-rendered HTML ...

Displaying Errors from Controllers in React Hook Forms

Currently, I am attempting to generate required errors for my input element that is enclosed within a Controller component from react-hook-form version 7. The Input consists of a Material-UI TextField structured like this; <Controller ...

Looking for visible elements in WebDriverIO?

Currently, I am developing a test suite using WebDriverIO for a website with multiple duplicate elements that are selectively displayed based on user interaction... For example, the site may contain five buttons that each open a tooltip. These tooltips ar ...

Debugging Node.js Routes in Visual Studio Code: A Step-by-Step Guide

My application is structured as follows: server.js router routes emails.js index.js In my index.js file, I define the route like this: module.exports = function (app) { app.use('/emails', require('./routes/emails& ...

The pagination component in React with Material-ui functions properly on a local environment, but encounters issues when deployed

Looking for some assistance with a persistent issue I've run into. Can anyone lend a hand? [x] The problem persists in the latest release. [x] After checking the repository's issues, I'm confident this is not a duplicate. Current Behavior ...

Public folder fonts in Next.js are being served with the incorrect content-type

I am experiencing an issue with my Next.js site where I am serving self-hosted fonts using @font-face. Locally, the fonts are loading correctly without errors and with the correct content-type, as shown here: However, once I deploy the site to a productio ...

"Converting domain names with punycode and utilizing Firebase for a

My current project involves updating a Firebase app with NextJS, and I've encountered an issue that needs to be resolved. Upon running the command: % npm run build I received the following message: (node:3719) [DEP0040] DeprecationWarning: The `pun ...

What are the advantages of polymer's inter-component data binding?

I am working on a login component and I want to ensure that the login status is accessible by other components within my application. Is there anyone who can share some functional code snippets or examples? I require a method for binding or event handlin ...

Value of the environmental variable not being interpreted

While exploring the world of environment variables, I encountered a puzzling issue. In my root project folder, I have two files named '.env.local' and '.env'. Strangely, the values in the '.env' file are not being processed, w ...

Struggled with setting up the WebSocket structure in typescript

Issue Running the code below results in an error: index.tsx import WebSocket from 'ws'; export default function Home() { const socket = new WebSocket('ws://localhost:1919/ws'); return ( <div>Home</div> ); } ...

React is having difficulty locating a specific module

I've been attempting to install the parallax library from https://github.com/wagerfield/parallax/. I have gone through the documentation and even found a sample usage in JavaScript. Planning to integrate it into React, based on the sample code and Rea ...