How to update router query in Next JS without triggering a page change event

I am seeking a solution to modify a URL query for the current page in Next JS without causing the page change event to trigger. Specifically, I need to be able to remember the week that is being viewed in a calendar, much like how Google Calendar operates. Here's what I have attempted so far:

import Calendar from '../components/Calendar'
import { formatDate } from '../utils'

class CalendarDashboardPage extends React.Component {
  refreshQuery(date) {
    const { pathname, asPath } = this.props.router
    const d = formatDate(date) // YYYY-MM-DD
    this.props.router.push(pathname, asPath, { query: { d }, shallow: true })
  }

  render() {
    return <Calendar onDateChange={this.refreshQuery) />
  }
}

export default withRouter(CalendarDashboardPage)

While my approach appears to be functional, using this.props.router.push triggers a page change in Next JS, which inadvertently displays the loading bar implemented (nprogress). In an attempt to resolve this issue, I experimented with

this.props.router.push({ query: { d } });
, but it did not produce the desired outcome.

Hence, my inquiry lies in finding out if there exists a method to adjust the router query without initiating events like routeChangeStart(url)?

Answer â„–1

If you want to monitor changes in the previous pathname and perform a conditional check within the routeChangeStart event handler, you can accomplish this by:

// _app.js

import Router from "next/router";

let previousPathname = null;

function handleRouteChange(url) {
  const pathname = url.split('?')[0];
  if (previousPathname && previousPathname !== pathname) {
    console.log(`App is changing from ${previousPathname} to ${pathname}...`);
  }
  previousPathname = pathname;
};

Router.events.on("routeChangeStart", handleRouteChange);

...

This approach may not directly solve your query as it will still trigger Router.events, but it could be beneficial for your specific scenario.

Answer â„–2

Unfortunately, it seems that changing the URL in the browser without reloading the page is not possible (as far as I know).

In order to accomplish this task, you will need to work within a single page application.

You may have to switch from using next/router to utilizing react-router. Check out this helpful article for more information on creating a single page application with next using react router.

Once you have made the transition, you can use

this.props.history.push("/new/url")
with the react router feature to achieve the desired functionality.

I hope this explanation is useful to you.

Answer â„–3

I found a simple solution by utilizing the browser's API.

updateDateQuery(date) {
  const formattedDate = formatDate(date); 
  window.history.pushState('', '', `?d=${formattedDate}`)
}

This code snippet updates the date parameter in the URL as users navigate through the calendar. It can then be accessed using componentDidMount() for refreshing or sharing the URL.

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

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

Enhance Your NextJs Website with Interactive Tooltips using @tippyjs/react

<Link href="/company/add" > <a title="My New Title" data-toggle='tooltip' className="btn btn-primary">My Link</a> </Link> Trying to integrate a Tippy tooltip component with a Nextjs Link do ...

Issue: It seems like there is an error with using functions as a React child. Uncertain about the exact location

This specific issue is one of the two errors I have come across in the same application referenced in my previous inquiry. The first error encountered is as follows: Warning: Functions are not valid as a React child. This may occur if you mistakenly return ...

Show data based on the chosen destination

Recently, I've been working on creating a simple printer manager to monitor the status of all my printers. Although I have successfully displayed all the data, I'm facing an issue while trying to organize it by location. The error message I keep ...

Is it possible for two node scripts running on the same machine to interfere with each other's execution

In the scenario where a parent node file (such as an express server) spawns child nodes that execute computationally intense tasks, will these children cause blocking for the parent process? ...

Customizing the appearance of React Navigation StackNavigator through background color changes and styling

Recently delving into React Native, I've managed to create a basic app with three different scenes. Initially, I used Navigator for navigation purposes, but found it to be sluggish and decided to give React Navigation (found at https://reactnavigation ...

Do I have to additionally check the data type using typeof when implementing PropTypes in my code?

I have a custom method called onNotifyChange that is triggered in the onChange event of an input element. This method has been defined with a PropType of func. MyComponent.propTypes = { onNotifyChange: PropTypes.func, } When invoking the onNotifyCha ...

Integrating threejs dynamically into a Create React App environment

When I am dynamically loading Three.js, the variable THREE is not found. I have created a React project using create-react-app and copied the three js file into the public folder. Here's the directory structure: src public ├── js │ └─┠...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

A guide to testing window.pageYoffset in webdriverIO using chai assertions

When conducting a selenium test using WebDriverIO and Chai, I encountered the need to capture the position of window.pageYoffset. Unfortunately, I was unable to find a direct way to do this in WebDriverIO. My initial attempts involved: browser.scroll(0, 2 ...

Send two arguments to a personalized validation function using express-validation

I have a requirement to input two values in order to search for a subdocument using the main document ID and then another ID of the subdocument. These IDs are received as parameters, and I am utilizing express-validator with a custom function to ensure th ...

Retrieving the maximum number and its corresponding name from an object using JavaScript

Check out my cool react app at this link: https://i.stack.imgur.com/9VpCd.jpg I've been working on a function to find the highest and lowest latitude along with the corresponding city names. Currently, I have successfully retrieved the latitudes but ...

When using NodeJS, having multiple 'if' statements may result in conflicting headers being returned,

Introduction to Promises. Encountering challenges in NodeJS due to the utilization of multiple if-statements and return-statements. Considering leveraging Promise as a potential solution. This snippet showcases an example: const express = require(' ...

The information returned to the callback function in Angular comes back null

In my Node.js application, I have set up an endpoint like this: usersRoute.get('/get', function(req, res) { //If no date was passed in - just use today's date var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd&ap ...

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...

Ways to exchange information among Vue components?

My role does not involve JavaScript development; instead, I focus on connecting the APIs I've created to front-end code written in Vue.js by a third party. Currently, I am struggling to determine the hierarchy between parent and child elements when ac ...

Invoking a Node.js function using a URL reference

Is there a way to call a function located in a remote URL? I have the page URL and the function name. The server-side application is running on NodeJs Express, and the function structure is as follows: function executer(param1, param2){ //logic re ...

The disappearance of hashtag (#) when passed as req.query in the backend has been observed

I am facing an issue where a string with a hashtag in the req.query is not being parsed correctly as JSON. http://localhost:3000/link/?items=[{"quantity":1,"_id":"00001","box":"item01","desc":&quo ...

Angular is having trouble with binding

What seems to be the issue in this code snippet? JSFiddle. function SecondCtrl($scope, Data) { $scope.data = Data; $scope.reversedMessage = function(message) { return message.split("").reverse().join(""); }; } ...

Angular does not delay for promises to settle

Issue I am facing is related to Angular not waiting for promises to be resolved. The console inspection reveals that the provider and skills objects are not retrieved before the promises are returned. I have included the key parts of the code below. The s ...