Updating dynamic parameter in a NextJS 13 application router: A complete guide

In my route user/[userId]/forms, I have a layout.tsx that includes a Select/Dropdown menu.

The dropdown menu has options with values representing different form IDs. When the user selects an item from the dropdown, I want to navigate to user/[userId]/forms/[formId]. Currently, I am attempting to achieve this as follows:

import { useRouter, usePathName, useParams } from "next/navigation";

const router = useRouter();
const pathName = usePathName();
const params = useParams();

const handleOnChange = (formId: string) => {
  if(params.formId) {
    router.push(pathName.replace(params.formId, formId)); // Update selected form.
  } else {
    router.push(`${pathName}/${formId}`); // Open new form.
  }
}

This method works, but it seems manual and potentially unreliable. If the URL contains a string matching the form ID, it could be unintentionally replaced. Is there a more robust way to set the value of a dynamic route segment?

Answer №1

Give router push a try, it was successful in my case.

 router.push(`${previousUserId}/forms/${updatedFormId]`);

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

Guide on retrieving data from an axios promise in JavaScript

I am struggling to manage the output of multiple lists retrieved through an axios API call made in JavaScript. I want to know how to effectively log the results and save them for future use, particularly for creating a data visualization. Here is my curre ...

Inject HTML entities, escaped for CSS, dynamically using JavaScript

My goal is to dynamically generate a list of HTMLElements with unique data-* attributes that correspond to various HTML Entities. These attributes will then be utilized by CSS to display content in pseudo elements like this: li:after { content: attr(dat ...

Accessing specific values from a JSON object in JavaScript

I'm fairly new to JSON and have a JSON String that I'd like to access and print to a DIV. I've managed to get it working using the following code snippet: document.getElementById("product_content").innerHTML=javascript_array[5].name; The s ...

Different methods of displaying the next image from a URL without explicitly setting the dimensions

I am attempting to display an image in Next.js without specifying the width and height by using import Image from 'next/image';. It should be noted that the image is sourced from a URL, not a specific folder within the project. <Image si ...

Jquery button click event is malfunctioning after the inclusion of jquery keyboard plugin

When I try to gather user input from a textbox using jQuery keyboard.js, the functionality works perfectly fine if I exclude the virtual keyboard code. For more information on keyboard.js, you can visit: https://github.com/Mottie/Keyboard/wiki Below is t ...

Running multiple controller functions in nodejs can be achieved by chaining them together in the desired

Currently, I am working on the boilerplate code of mean.io and adding a password reset email feature to it. Whenever a user requests a password reset with their email as a parameter, I generate a unique salt (resetid) and send them an email with a link con ...

The Vue pagination component is optimized to load a single page at a time

There seems to be an issue with my paginate component as it is only displaying the first page despite the total number of objects I want to show: Pagination Component Code: <paginate v-if="searchResults.length >0" class="m-2"> ...

Is it possible to have a div set to close upon loading the page?

Is there a way to have the toggle function set up so that when the page loads, the div being toggled starts out closed? I don't want them to be visible until clicked on. Best regards, Joey <script type="text/javascript> $(document ...

Tips for incorporating asynchronous page components as a child element in next.js?

Utilizing the latest functionality in next.js for server-side rendering, I am converting my component to be async as per the documentation. Here is a simple example of my page component: export default async function Home() { const res = await fetch( ...

What is the starting point of a Next.js application?

When deploying a nextjs app on c-panel hosting, it requires the entry point of the application which is typically set as app.js by default. In a regular React application, you have full control over this aspect, but with nextjs, it's not always clear ...

Tips for incorporating a dynamic basePath into your NextJS project

For my new app, I am trying to include the groupID in the URL before the actual path, such as 'https://web-site.com/1/tasks'. The NextJs docs mention a basePath that is set at build time and cannot be modified. With numerous routes in my current ...

A technique for calculating the total quantity of each item individually while using v-for in VueJS

Struggling to code (complete newbie) using VueJS and facing a major roadblock. I have a list of orders and I need to sum the quantities of each item separately. The only way to access the items is through v-for. <tr> <td data-th="list"> < ...

Rotate an object upwards in three.js in order to achieve dynamic movement and enhance

I'm struggling with 3D calculations and could really use some assistance. In my scene, I have a sphere representing the earth and I'm using OrbitControl to "rotate" it (although in reality, OrbitControl rotates the camera). I need a function, s ...

Is there a way to showcase an epub format book using only HTML5, CSS, and jQuery?

Can ePub format books be displayed in a web browser using only HTML5, CSS, and jQuery? I would appreciate any suggestions on how to accomplish this. Additionally, it needs to be responsive so that it can work on iPad. While I am aware of this requirement, ...

Issue with HighCharts Series Data Points Not Being Added

I am currently facing a major challenge in dynamically changing data for highcharts based on date. To provide context for my project, it involves logging system data with timestamps. I have implemented a date and time picker to specify the start and end da ...

Error TS2322: Cannot assign type 'Promise<Hero | undefined>' to type 'Promise<Hero>'

I am currently studying angular4 using the angular tutorial. Here is a function to retrieve a hero from a service: @Injectable() export class HeroService { getHeroes(): Promise<Hero[]> { return new Promise(resolve => { // ...

Using callback functions to handle parameters in GET requests

Hey there, I'm currently diving into the world of callback functions and I have a burning question that needs clarification. Adding event listeners seems easy enough: $0.addEventListener("click", function(event){console.log(event)}); When you click s ...

Troubleshooting difficulties integrating NodeJS with R using an R script

I have been attempting to execute an R-script from a js-file but I am consistently receiving a null value as the return. Here is my folder structure: -R_test --example.js --helloWorld.R The contents of example.js are as follows: var R = require(" ...

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

Concentrate on the disappeared div element following the AJAX request

Encountering an unusual issue here that has me a bit puzzled. In one of my DIV elements, I have included several links which trigger an AJAX call (using jQuery) upon being clicked. The server (Controller) then responds with HTML content, specifically a JS ...