Next.js implementation of dynamic routing

Hello, I'm currently facing a challenge while working with dynamic routes in Next.js. The file in question is named [type].js, and it contains the following code:

import React from 'react';
import AuthSection from 'components/AuthSection';
import { useRouter } from 'next/router';
import { useAuth } from "../../util/auth";

function AuthPage(props) {
  const router = useRouter();
  const auth = useAuth();
  let getAuthRoles = auth.user ? auth.user.roles[0] : ""
  let pageSrc = ""

  if(getAuthRoles === "Moderation Staff"){
    pageSrc = "/moderation"
  }else if(getAuthRoles === "Super Admin"){
    pageSrc = "/superUser"
  }

  return (
    <AuthSection
      bgColor="default"
      size="medium"
      bgImage=""
      bgImageOpacity={1}
      type={router.query.type}
      afterAuthPath={router.query.next || `${pageSrc}`}
    />
  );

}
  1. Extracting authorization roles from Auth0.
  2. Using a ternary condition to fetch user roles for processing and transmission.
  3. A conditional statement that redirects users based on their assigned roles.
  4. A component generating the sign-in route, utilizing page routing logic.

If I utilize the snippet below:

return (
    <AuthSection
      bgColor="default"
      size="medium"
      bgImage=""
      bgImageOpacity={1}
      type={router.query.type}
      afterAuthPath={router.query.next || '/moderation'}
    />
  );

This works flawlessly, but it does not meet my requirements.

Essentially, I need the application to dynamically redirect users to specific pages based on their roles. From my Javascript perspective, incorporating a dynamic route into the afterAuthPath seems logical. However, this approach results in an error like the one shown here:

https://i.sstatic.net/9NUWa.png

Upon consulting the documentation, I realized it primarily explains the usage of href, which is not applicable in my case.

How can I address this issue? I'm currently at a loss for alternative solutions and would greatly appreciate your assistance!

EDIT: Below is the code for my AuthSection.js component:

import React from "react";
import Section from "components/Section";
import Container from "@material-ui/core/Container";
import SectionHeader from "components/SectionHeader";
import Auth from "components/Auth";

function AuthSection(props) {
  // Configuration values for each authentication type
  const allTypeValues = {
    signin: {
      title: "Welcome back",
      buttonText: "Sign in",
      linkTextSignup: "Create an account",
      linkTextForgotpass: "Forgot Password?",
    },
    signup: {
      title: "Get yourself an account",
      buttonText: "Sign up",
      linkTextSignin: "Sign in",
    },
    forgotpass: {
      title: "Get a new password",
      buttonText: "Reset password",
    },
    changepass: {
      title: "Choose a new password",
      buttonText: "Change password",
    },
  };

  // Validating the current authentication type
  const currentType = allTypeValues[props.type] ? props.type : "signup";

  // Retrieving values for the current authentication type
  const typeValues = allTypeValues[currentType];

  return (
    <Section
      bgColor={props.bgColor}
      size={props.size}
      bgImage={props.bgImage}
      bgImageOpacity={props.bgImageOpacity}
    >
      <Container maxWidth="xs">
        <SectionHeader
          title={allTypeValues[currentType].title}
          subtitle=""
          size={4}
          textAlign="center"
        />
        <Auth
          type={currentType}
          typeValues={typeValues}
          providers={props.providers}
          afterAuthPath={props.afterAuthPath}
          key={currentType}
        />
      </Container>
    </Section>
  );
}

export default AuthSection;

UPDATE - Revised Code

import React, { useEffect, useState } from "react";
import AuthSection from 'components/AuthSection';
import { useRouter } from 'next/router';
import { useAuth } from "../../util/auth";

function AuthPage(props) {
  const router = useRouter();
  const auth = useAuth();
  const [pageSrc, setPageSrc] = useState("");

  useEffect(() => {
    const getAuthRoles = auth.user ? auth.user.roles[0] : "";
    let newPageSrc = "";
  
    if(getAuthRoles === "Moderation Staff"){
      newPageSrc = "/moderation"
    } else if(getAuthRoles === "Super Admin"){
      newPageSrc = "/superUser"
    }
  
    setPageSrc(newPageSrc);
  }, [auth]);

  return (
    <AuthSection
      bgColor="default"
      size="medium"
      bgImage=""
      bgImageOpacity={1}
      type={router.query.type}
      afterAuthPath={router.query.next || `${pageSrc}`}
    />
  );

}

Answer №1

useRouter is a hook.

What do you think of this piece of code?

const [pageSrc, setPageSrc] = useState("");

useEffect(() => {
  const getAuthRoles = auth.user ? auth.user.roles[0] : "";
  let newPageSrc = "";

  if(getAuthRoles === "Moderation Staff"){
    newPageSrc = "/moderation"
  }else if(getAuthRoles === "Super Admin"){
    newPageSrc = "/superUser"
  }

  setPageSrc(newPageSrc);
}, [auth]);

useRouter is a React Hook and cannot be used with classes. You have the option to use withRouter or convert your class into a function component.

Learn more about useRouter here

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

Tips for updating a specific field within an object in an array within a mongoose schema and persisting the changes

I am currently developing a website where users can sign in, create tasks, and mark them as done. I am using mongoose to work with the data, specifically saving tasks inside an array of type Task in a User model. Each task has a "done" value which is repre ...

What could be the reason for my Ajax failing to send the data to the external file?

My current setup involves sending data to an external PHP file via AJAX in order to generate a PDF using TCPDF and return it back to the page. However, I seem to be facing some issues with this process. Despite my efforts, I am unable to pinpoint the mist ...

Handling an HTML Form without the Submit Button using VeeValidate

I've implemented a form handler using its composable feature in my <script setup>: const { submitForm, resetForm, handleSubmit, meta } = useForm() function save() { // Want to submit the form here submitForm() // Not working showSaveSnac ...

The unprojection of the vector in Threejs from this camera has not been defined

Why am I encountering a "function is undefined" error for vector.unproject even though it is clearly mentioned in the documentation? You can find it here: (one of the last items) Even after console logging it, the function still returns as undefined, des ...

Can you explain the distinction between using this.function and making a function call in React?

I'm new to React and recently came across some code in a project that confused me. Could someone please clarify the distinction between this.function and the following function call used in a React event handling prop? <button onClick={this.clickH ...

Can you help me convert this Mongoose code to use promises?

Using Mongoose's built-in promise support, I aim to streamline the process of a user sending a friend request to another user. However, even with careful error handling and sequencing in place, I find myself grappling with a slightly condensed pyramid ...

Will terminating a Google Cloud Storage stream impact network usage?

As part of my project, I am developing a media server that will serve streamable audio files. To reduce the number of requests to Google Cloud Storage, I have implemented a caching system. However, one issue I've encountered is that Chrome sends two ...

What is the best method for locating the innermost element of an HTML tree that has a specific class assigned

I am working on a project that involves a menu system. One of the features I am implementing is that when a tree within the menu is opened, it receives the "active" class. My goal now is to dynamically retrieve the deepest sub-menu within this structure ...

What is the best way to incorporate a logo container and a horizontal divider into my top navigation bar using Bootstrap?

I'm currently working on designing a top navigation bar that features a logo with color #1 as the background on the left side. The logo is then separated by a grey horizontal divider, followed by color #2 representing the application name beside the d ...

Utilize the HTML webpack plugin to include the rendered file within the router

Hey there! I'm currently dealing with a frustrating issue. I can't seem to locate the index.html file generated by html-webpack-plugin for rendering. Even though I can access it at localhost:8080/index.html, I'm struggling to figure out how ...

Determine the value of an object by iterating through its keys

UPDATE: (for clarification) I currently have a table named modelCoa +----+----------+-------+--------------------+ | id | id_parent| code | name | +----+----------+-------+--------------------+ | 1 | 0 | 1 | asset ...

Effect fails to activate on the third occurrence of the action

After successfully running on the first two action dispatches, the effects fail to trigger on the third time. I have tried the solutions provided in this thread and here, but none of them work for me. Here is the relevant code snippet: @Effect() get ...

At what point does the cleanup function in UseEffect activate the clearInterval() function?

In the process of creating a timer for a Tenzie game, there is an onClick function that changes the state of isTimerActive from false to true when a user clicks a button. The initial value of tenzie state is also set to false, but once the user completes t ...

Display JSON data using Vue.js

Trying to display JSON file results using Vue.js, with the goal of showing the result in a value. Here is the code snippet: data () { return { fetchData: function () { var self = this; self.$http.get("/api/casetotalactivation", functio ...

Tips for utilizing components in slots in Cypress and Vue for effective component testing

Can someone help me figure out how to import a component into a slot using Cypress Component Testing with Vue? The documentation mentions the following for slots: import DefaultSlot from './DefaultSlot.vue' describe('<DefaultSlot />& ...

Protractor is unable to locate the password input field on Gmail using its ID

Currently, I am in the process of configuring Protractor to test my application. However, I am encountering a roadblock as it requires authentication through Gmail and I am struggling with the login process: describe('Vivace Home page', function ...

How AngularFire automatically adds back a removed item in a Firebase array

I have been working on a way to remove an item from my $firebaseArray called "boxes". Here is the "remove" function: function remove(boxJson) { return boxes.$remove(boxJson); } Although it gets removed, I noticed that it immediately reappea ...

The jQuery hover function is not functioning properly on page load in Firefox

While this code is functioning smoothly in Chrome and IE, it seems to be encountering issues in Firefox! <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> JS: $(window).load(function(){ $("#bosti ...

The transformation in the resulting array is evident when a nested array is altered after being concatenated using Array.concat

MDN explains concat as follows: The concat() function is utilized to combine two or more arrays without altering the original arrays. Instead, it produces a new array. Let's examine the code snippet below: Example 1 const array1 = [['a& ...

Removing a key from an index signature in Typescript - a step-by-step guide

In my web application built with Angular, we encountered a need for a data type to store translations of strings in different languages. To address this requirement, a team member defined the following type: export class TranslatedString { [language: str ...