Issue with NextJs query parameters receiving incorrect values upon dynamic updates

On my page, there are default query parameters set as '?status=default'

I'm attempting to retrieve the status value dynamically change it using a button trigger

Initially, when the page loads for the first time, it correctly displays the value as 'default'

https://i.sstatic.net/5Y5Pf.png

However, when I try to change the status using an onClick button, the URL behaves as expected, but the value does not update

https://i.sstatic.net/ViVok.png

Below is the code snippet:


import React, { useEffect } from 'react'
import { GetServerSidePropsContext } from 'next'
import { useRouter } from 'next/router'

const TestURL = (props: any) => {
  const router = useRouter()
  const { query } = router

  function handleChangeQueryParams(status: string) {
    router.replace(router.asPath, { query: { status } })
  }

  console.count('rerender')
  console.log(query.status)

  return (
    <div className="flex flex-col gap-4">
      Index
      <button>{query.status}</button>
      <button
        onClick={() => handleChangeQueryParams('Test1')}
        className="border&qout;
      >
        change query params
      </button>
      <button
        onClick={() => handleChangeQueryParams('Test2')}
        className="border&qout;
      >
        change query params2
      </button>
    </div>
  )
}

I've tried using useEffect and useState, but it doesn't seem to be working correctly. What am I missing here?


  const [status, setStatus] = useState(query.status)
  useEffect(() => {
    setStatus(query.status)
  }, [query.status])

Answer №1

After experimenting with various approaches, I discovered that the issue was with

router.replace(router.asPath, { query: { status } })

Once I switched it to

 router.replace({
  pathname: 'test',
  query: { status },
 })

it functioned correctly

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

Utilize Vue's prop system to pass objects between components

Can you help with passing objects as props in Vue? It seems like a simple task, but I'm having some trouble. In my .vue file, I have the following code: <template> <div id="scatter"></div> </template> <script&g ...

Is there a way to position the menu above the button?

I need some help with my menu. Currently, it is showing up below the button and within my footer instead of above the content like I want it to. If anyone can assist me in understanding what I am doing wrong, I would greatly appreciate it. Thank you for ta ...

Toggle the checkbox to update the count

I am trying to implement a feature where the user can check a maximum of 4 checkboxes. I have managed to achieve this functionality in the code below. When the user unchecks a box, the count should decrease by one and they should be able to check another c ...

The static files for the icon CSS (404 Error) from Flaticon and Font-mfizz are failing to load properly

When I was designing a website, I needed an icon of Python, so I turned to Flaticon and found what I was looking for. This snippet shows the HTML code I used: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <li ...

What could be the reason for the absence of {{ list.title }} on display

I'm currently learning how to develop my first MEAN stack app by following a tutorial on YouTube. However, I've encountered an issue where the title of the list is not displaying correctly. I'm using Insomnia to create the lists. Here's ...

Whenever I run "npm run build-dev" in Webpack with JavaScript, the browser continuously refreshes

I've been working on familiarizing myself with webpack lately. I've managed to convert everything to load modules and plugins, and it's all working fine when I use "npm run build-prod". Even when I use liveServer, the HTML loads properly. Ho ...

Troubleshooting base href issues in AngularJS routing

For a demonstration, I decided to try out this plunker from a tutorial that showcases tab routing across different pages. After downloading the entire zip file and running it as is (e.g. with all files in the same directory and utilizing CDN links), I enco ...

Display a modal across all pages by incorporating a button component, regardless of its placement

I've implemented a header in my react app with a show dialog button that appears on all necessary pages. Currently, my approach to displaying the dialog is as follows: When the user clicks the button, I dispatch an action to the redux store { type:S ...

Error: Trying to access the length property of an undefined or null reference in JSON formatted data fetched through Ajax

I am attempting to populate a jQuery DataTables with JSON data retrieved from a Web API ajax call, but encountering the following error: An unhandled exception occurred at line 38, column 314 in 0x800a138f - JavaScript runtime error: Unable to get proper ...

Looking to display a JSON-based menu using AngularJS?

Having trouble displaying a dropdown menu when trying to print a menu from a JSON file. https://i.sstatic.net/fNLxw.png JSON Data [{ "Option": "Request", "Name": "<a href=\"#/request\"><i class=\"material-icons left\ ...

Javascript function to deselect all items

One of my functions is designed to reset all checkbox values and then trigger an AJAX request. However, there are instances when the function initiates before the checkboxes have been unchecked. function clear() { $("#a").prop("checked", false); $("#b ...

What is the best way to conceal a Boostrap Navbar using jQuery?

Attempting to create a hidden side navbar using Jquery and Bootstrap 4. Struggling with the .on('click', ...) event handler for a button not hiding the sidebar as expected despite all files loading correctly according to the developer tools. Atte ...

Can someone explain the variance between these two script codes? Are they entirely distinct, or can I utilize just one source?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> It appears that one script is for jQuery and the ...

Transferring data between actions following an AJAX request in Zend Framework

I am currently utilizing an ajax call to communicate with a controller in order to update the number of articles displayed on the webpage. I have established an action within the controller to handle this ajax request. Below is a snippet of the code: publ ...

How can I allow the background image of a div to be edited in the Experience Editor with Sitecore NextJS?

I have designed a custom component in Sitecore Next Js React that serves as a full-width banner. I am looking to add an image as the background of the parent dive, and this image should be easily editable through the experience editor. Can anyone provide ...

ScriptManager is not accessible in the current ASP.Net Core Razor Page context

I'm facing an issue where I have a view (such as Index.cshtml) and a page model (like Index.cshtml.cs). In the view, there's a JavaScript function that I want to call from the OnPost() method in the page model. I tried using ScriptManager for thi ...

How can I keep a div open when the mouse hovers over it, and then close it when the mouse

My current markup looks like this: <div class="wrapper-header"> <div class="container"> <div class="navbar"> <ul class="nav navbar-nav"> <li class=""><a href="#" class="toggle">Show Categories</a></li> </ ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

Ending a Firestore `get` query upon unmounting component

Currently, I am retrieving data from Firestore in the componentDidMount function. However, if I happen to change the component while it is still in the process of fetching data, an error occurs: Warning: Can't call setState (or forceUpdate) on an u ...

Is there a way to stop "window.location.replace()" from being replaced or overridden?

Is there a method to safeguard against alterations or overrides of window.location.replace()? For instance, attempting to change it like this: window.location.replace = function(){ return "Hi" }. Initially, I experimented with using Object.free ...