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

The behavior of Date's constructor differs when applied to trimmed versus untrimmed strings

Although it's commonly advised against creating a date from a string, I stumbled upon an interesting phenomenon: adding a space before or after the date string can impact the resulting date value. console.log([ new Date('2019-03'), ...

Preventing content shift during exit animations using Framer Motion and NextJS

I'm encountering an issue on my website where one specific page experiences a layout shift when visiting another page. This problem doesn't occur on any other pages, and I'm struggling to identify the root cause. If anyone has insights or su ...

What is the best method for determining values within JSON data?

In my possession is a JSON file containing user data that looks like this: [ { "id": 0, "username": "Antony", "users": [ { "id& ...

Experiencing challenges while transitioning to Material UI version 5 with datepicker and Next.js

Encountering an error with Module not found: Can't resolve 'luxon' when implementing LocalizationProvider with AdapterLuxon and Next I suspect there may be a mistake in my setup somewhere. Here is the codesandbox link showcasing the issue: ...

The error message "Cannot access 'id' property of undefined" is being displayed

I have a file named auth.js along with a middleware called fetchuser. The code provided below is causing an error that I cannot figure out. The error occurs during the process of sending a token to the user and verifying whether the user is logged in or n ...

A guide on incorporating JavaScript variables within a GraphQL-tag mutation

I'm having trouble consistently using javascript variables inside graphql-tag queries and mutations when setting up an apollo server. Here's a specific issue I've encountered: gql` mutation SetDeviceFirebaseToken { SetDeviceFirebaseTok ...

Evolution of ReactJS state over time

When working with React, I wanted to increment a state variable called progressValue by 0.1 every 500 ms until it reaches 100. Here's what I initially tried: const [progressValue, setProgressValue] = React.useState<number>(0) const tick ...

"Exploring the dynamic duo of Angular2 and ng2Material

I am currently facing an issue with the styling in my code while using ng2Material with Angular2. First: A demonstration of Material style functioning properly can be seen in this plunker. When you click on the button, you will notice an animation effect. ...

Troubleshooting: Why are my images not displaying in webpack and node.js setup?

My problem: I'm facing an issue with background images in my project. I have included two images and used file-loader to bundle them through webpack. While the images display correctly in the app during development using webpack-dev-server, they disap ...

What is the best way to continue looping until my variable matches the user's input? JavaScript

As of now, this nested for loop continues until both i and j reach 3. How can I reset the variables once they have reached their maximum value so that the loop can continue running? Alternatively, is my current approach incorrect? for (i=1; i<=3; i=i+ ...

Why am I unable to export dynamic routes with "use client" in Next.js 13 when using the App Router?

I am currently working with Next.js 13 using the App Router and have a page that utilizes dynamic routes. Everything runs smoothly when I test the server locally (e.g., localhost:3000//tickets/2), but I encounter prerender errors when attempting to export ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...

I'm having trouble getting my window resize event listener to function properly. I'm using a combination of Three.js and Vuetify.js

My goal is to incorporate a three.js renderer into a div element using the vuetify.js framework. I want my code to dynamically adjust the dimensions of the div element whenever the window is resized. I have excluded unnecessary code blocks from this excer ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

What is the best way to choose the initial element in every group using jQuery?

If we have the following HTML input: <p>A</p> <p>B</p> <p>C</p> <div>D</div> <p>E</p> <p>F</p> <p>G</p> We can select B, C, F and G using the following code: $('p + ...

What are the steps to integrate the aws-iot-device-sdk NPM module with Angular 11? I am encountering errors related to fs, path, and tls during the build process

I manage a browser-based Angular application that was previously on version 5.6. This app consists of two components that subscribe to an IOT topic and listen for updates without publishing. The task at hand is to upgrade to Angular 11.0.3, which I have c ...

Is there a tool available that can convert the string "foo:blah" into JSON format?

My goal is to transform a human-readable list like the following: Enabled: Yes Server: example.com Port: 8080 Authenticated Proxy Enabled: 1 ... into a sanitized JSON object as shown below: { "Enabled": "Yes", "Server": "example.com", "Port" ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

Next.js 13 does not support the use of GetStaticProp feature

I followed an online tutorial that uses the older version of Next.js. However, I am now using Next.js 13 and attempted to utilize GetStaticProp() for fetching data from my API. Unfortunately, I encountered an issue where I cannot use that function under th ...

What are the implications of an unidentified callback function with parameters?

Check out this snippet: const fs = require('fs'); fs.readFile('foo.txt', 'utf8', (error, data) => { if (error) { throw new Error(error); } console.log(data); }); Can you figure out where the anonymous callback is recei ...