Exploring the benefits of Next Js 13 for effective website

Is there a way to dynamically add and remove query parameters using Next Js useRouter from the "next/navigation" library while utilizing App Routing? I am looking to include a filter in the query, like adding filters=219,213 with .../hotels?id=123&type=hotel

I attempted to use router replace to add new query parameters

Answer №1

To retrieve the query and pathname, you will need to utilize the functions useSearchParams and usePathname. If you wish to update an existing history record instead of adding a new one, you can use router.replace.

'use client'

import { usePathname, useRouter, useSearchParams } from 'next/navigation'

export default function Page() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const router = useRouter()

  const updateQuery = () => {
    const newUrlParams = new URLSearchParams(searchParams.toString())
    newUrlParams.set('filters', ['219', '213'].join(','))
    router.push(`${pathname}?${newUrlParams}`)
  }

  return (
    <div>
      <button onClick={updateQuery}>Update filter</button>
    </div>
  )
}

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

Maximizing the potential of a cell in a table

I am currently using AJAX to retrieve and display data in my table. However, I want to capture the actual value from the selected cell in the table. To better display user needs, I have split the returned value to obtain specific items. Below is the scri ...

Looking for assistance in reducing the vertical spacing between divs within a grid layout

Currently, I am in the process of developing a fluid grid section to showcase events. To ensure responsiveness on varying screen resolutions, I have incorporated media queries that adjust the size of the div elements accordingly. When all the divs are unif ...

Autocomplete's `getOptionLabel` function unexpectedly returned an object ([object Object]) instead of the expected string

Currently delving into the world of ReactJS and working with @mui controls, specifically a Multiselect Dropdown with autocomplete feature. Here is the child component causing me some trouble, displaying the following error message: "index.js:1 Materi ...

Fetching server-side JavaScript source from a relative path within an ASP file

My setup involves a local IIS server pointing to a virtual workspace at c:\projects Within my c:\projects directory, I have the following folder structure: Game src asp test.asp jquery jquery.min.js The test ...

Next JS rewrites may be functioning smoothly in a local environment, however, they appear to encounter issues after deployment on Verc

Here's a glimpse of my next.config.js configuration => { async rewrites() { return [ { source: '/:path*', destination: `/:path*`, }, { source: '/sell', destination: `${ ...

Steps for generating a time selection dropdown menu

My issue is with the functionality of my timepicker dropdown. Below is the code I am currently using: $(document).ready(function() { $('.timepicker-input').timepicker({ timeFormat: 'h:mm p', interval: 60, minTime: ' ...

Issues with styled-components media queries not functioning as expected

While working on my React project with styled components, I have encountered an issue where media queries are not being applied. Interestingly, the snippet below works perfectly when using regular CSS: import styled from 'styled-components'; exp ...

AJAX requests sent from different origins to AWS S3 may encounter CORS errors on occasion

My current objective is to access publicly available files stored in S3. The CORS configuration for my S3 setup is as follows: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> < ...

Navigating through route parameters and application logic

There is an endpoint / which may receive different get parameters for oAuth and logging in to an app. A function called queryAction has been created to handle these requests. Platforms like express can route at the path level but not the res.query level, ...

Getting the value of a CSS Variable from Radix UI Colors with Javascript/Typescript: A step-by-step guide

Currently, I am attempting to dynamically retrieve the Radix Colors values in JavaScript. The reason for this requirement is that I generate these colors based on user input, resulting in values that are variable. As a result, I cannot hardcode the values. ...

Please only submit the form if the check box has been ticked

<div id="checkbox"> <input type="checkbox" id="1" name="1"/><br/> <input type="checkbox" id="2" name="2"/><br/> <input type="checkbox" id="3" name="3"/><br/> <input type="submit" value="Create"/> </div ...

What sort of JavaScript WYSIWYG text editor provides formula support?

Looking for a Javascript rich text editor that offers formula selection in the toolbar. Any recommendations? ...

Reaching out to the Edge: Enhancing the jQuery Slider Experience

Alright, I'm really excited about using this amazing slider. What I love most is the "free mode" feature that creates this stunning sliding effect. The size and number of slides are absolutely perfect for me. But there's just one small adjustment ...

Oops! There seems to be an issue with an invalid character in the literal true value while making a POST request to the API with JSON data. The expected character should be

Can anyone help me solve an issue I am facing while trying to use the POST method to insert data using JSON in JS code? When I attempt the transformation, I receive an error message stating: "ERROR: invalid character ' ' in literal true (e ...

Navigating the NextJS App Directory: Tips for Sending Middleware Data to a page.tsx File

These are the repositories linked to this question. Client - https://github.com/Phillip-England/plank-steady Server - https://github.com/Phillip-England/squid-tank Firstly, thank you for taking the time. Your help is much appreciated. Here's what I ...

Event handling in Node.js can sometimes result in throwing exceptions

I need advice on how to handle errors or return values from an event in my code. Here is what it looks like: _initConnection(){ try{ const errorValidation = this.errorValidation const HOST = "192.168.2.32" ...

Does combineLatest detach this from an angular service function?

Check out this test service on Stackblitz! It utilizes the combineLatest method inside the constructor to invoke a service method: constructor() { console.log("TEST SERVICE CONSTRUCTED") this.setParameters.bind(this) this.assignFixedParamete ...

Guide for redirecting puppeteers' attention to a new pop-up interface

Currently, I am utilizing Puppeteer to carry out a test on a website. Upon clicking a button, a new popup browser window emerges displaying a report. Inside this new window lies data that I wish to extract. Is there a method for Puppeteer to switch its foc ...

Can VueJS 1 and 2 be integrated within the same package.json configuration?

At the moment, my JavaScript files are using VueJS 1. However, I am preparing to work on a new section of the system and want to switch to VueJS 2. ...

Repeatedly prioritize functionality

I have a Node.js application that includes logging functionality. Currently, I am calling this code in every module instead of using console.log. My question: I am not satisfied with this approach. Is there a more efficient way to implement logging in Nod ...