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

Improving the App() function in React and Typescipt

When working on my React/Typescript app, I encountered a challenge with the length of the code in one of the sections. Despite watching tutorials and searching for solutions, I couldn't find a clear way to refactor it. The specific issue is with refa ...

"Encountering an Issue with Storing Private Key as a String in NodeJS: Saving to .txt Results in Writing "[

Currently, I am attempting to save an EC key pair from the elliptic library as a string in a .txt file. However, when I do this, it ends up writing ""[object Object]"" to the file. UPDATE: Just wanted to note that the issue of turning the object ...

Set markers at specific locations like "breadcrumbs" and generate a route using Google Maps API v3.exp

I'm developing a new iOS application for scouting out locations while on the move. I want users to be able to mark each location by simply clicking a button, which will drop a marker based on their current location. The ultimate goal is to connect all ...

Angular: Issue with click() event not functioning properly once dynamic HTML is rendered

There are a few HTML elements being loaded from the server side, and an Angular click() event is also included. However, the event is not firing after the elements are rendered. It is understood that the DOM needs to be notified, but this cannot be done. ...

Unable to send information to a function (using jQuery)

I'm struggling to pass the result successfully to another function, as it keeps returning an undefined value: function tagCustomer(email, tags) { var o = new Object(); o.tags = tags; o.email = email; o.current_tags = getCustomerTags(email ...

redirecting from an AJAX request

Seeking a way to perform a redirect following an ajax `put` request. My intention is to implement client-side validation using pure JS. Client: $(document).ready(function() { login = () => { var username = $("[name='username']"). ...

Functions for abbreviating and combining strings in Javascript

Looking for help to simplify and shorten a Javascript function: $scope.doRefresh = function (){ if($scope.bulletpointPopular){ ArticleService.popular().then(function(data){ $scope.articles = data; }) .finally(function() { ...

Is there a way to dynamically assign column names during the import process?

In my current scenario, I am importing data from various sources into my JSON backend. The mapping file will resemble the sample below. The question is how can I efficiently utilize this mapping during data import into my backend. The idea is to provide t ...

The absence of a closing parentheses in the argument is causing an issue when rendering

Apologies for the basic mistake, but I could really use some assistance with this syntax error. I've spent over an hour searching for it and still haven't been able to locate the issue. It seems to be around the success function(data) section. Th ...

"Strategically placing elements on an HTML grid

My current project involves creating a grid layout in HTML using CSS. The goal is to use this layout for various elements such as images, text, and links. What I envision is a visually appealing grid where each object fits together seamlessly with no gaps ...

What is the best way to retrieve the Axios response using Express?

I've recently delved into working with Express and I'm currently struggling with making an Axios request using route parameters, and then updating some local variables based on the response. Here's a snippet of what I've been working on ...

How to automatically refresh a page when the URL changes with Next.js router?

On my page, users have the option to narrow down their search using filters. However, there is an issue where if a user selects a filter for "rent" or "buy", the URL does not automatically refresh to reflect the changes. Even though the changes are reflect ...

What is the best way to set up a session using jQuery?

I've been troubleshooting my code and I can't seem to figure out why the jquery.session.js file isn't working. Can someone help me find a solution? $.session.set('rmng_time', remaining_seconds); alert("j session "+$.sessi ...

ran into the error that this state is not a function

Every time I run my code, I encounter the error message this.setState is not a function. Can anyone offer guidance on how to fix this issue? Thank you! spiele.listUsers(params, function(err, data) { if (err) console.log(err, err.stack); else con ...

Menu selection that changes dynamically based on radio button selection

Currently, I have four radio buttons and my goal is to have a drop-down menu change based on the selected radio button. Should I pre-write all the drop-down options and display them accordingly, or would it be better to use ajax to fetch the values from th ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

Returning to the previous page

Having some trouble navigating back to the previous page. When I click the cancel button, it runs a function that uses history.back();, which works correctly. However, there is a validation on the page, so it checks all fields before navigating back. I&ap ...

find the middle element in the Vue array

Currently in the process of developing a custom Vue carousel component, I have utilized some code snippets from this resource: link My goal right now is to enhance the slider with additional navigation bullets. However, due to the justify-content:center p ...

sequenced pauses within a sequence of interconnected methods in a class

scenario: There are two javascript classes stored in separate files, each utilizing a different external service and being called within an express.js router. Refer to the "problematic code" section below: route routes.post('/aws', upload.sing ...

Is there a way to conceal the article container?

My experience with javascript and Mapbox is still limited, so please bear with me. I am currently working on a map that showcases various restaurants in NYC and their impact during the recession. Additionally, I am trying to include small columns for artic ...