Exploring the process of navigating between pages in Next.js using react-router-dom

Whenever a successful login occurs, I want to redirect the user to a different page. However, I am encountering an error message:

https://i.sstatic.net/Wi8XW.png

This is the snippet of code that is causing the issue:

export default function SignUp() {
  const trigger = async (event: any) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const navigate = useNavigate();
    try {
      const response = await fetchRestEndpoint(`/users`, 'POST', {
        username: data.get("username"),
        email: data.get("email"),
        password: data.get("password"),
        role: "user"
      });
    if (response.ok) {
      const user: any = await response.json();
      console.log(user);
      navigate('/');
    }
  } catch(e) {
    alert(e);
  }
  ......

Answer №1

Next.js has its own built-in router, eliminating the need for react-router-dom. I highly suggest exploring the associated documentation for more insight.

Utilizing the pages directory

import { useCallback } from "react";
import { useRouter } from "next/router";

const MyComponent = () => {
  const router = useRouter();

  const login = useCallback(() => {
    // ...
    router.push("/some-url")
  }, [router]);

  return (
    // ...
  );
}

When utilizing the app directory

import { useCallback } from "react";
import { useRouter } from "next/navigation";

const MyComponent = () => {
  const router = useRouter();

  const login = useCallback(() => {
    // ...
    router.push("/some-url")
  }, [router]);

  return (
    // ...
  );
}

Answer №2

It appears that there is an issue with violating the rules of React hooks by invoking a React hook within a callback function. React hooks should only be invoked at the top level, such as within the body of a React function component or a custom React hook.

To resolve this issue, move the useNavigate hook outside of the callback.

export default function SignUp() {
  const navigate = useNavigate(); // <-- call in function body

  const trigger = async (event: any) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);

    try {
      const response = await fetchRestEndpoint("/users", "POST", {
        username: data.get("username"),
        email: data.get("email"),
        password: data.get("password"),
        role: "user"
      });

      if (response.ok) {
        const user: any = await response.json();
        console.log(user);
        navigate('/');
      }
    } catch(e) {
      alert(e);
    }

  ...

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

Unreliable Environment Variable Behavior in Next.js 13.4 App Deployed on Cloud Run

Recently, I've been facing a perplexing issue with environment variables in my Next.js app deployed on Cloud Run. Despite working fine most of the time, there are random occurrences when these variables become undefined for no apparent reason. Strange ...

Guide to Dynamically Including an Element in an Array using Typescript

Encountering a type error within the <RenderFormFields formFields={formFieldsData} /> component:- Types of property 'type' are not compatible. Type 'string' cannot be assigned to type '"select"'.ts(2322) Rende ...

Using TypeScript path aliases to resolve import errors

After creating a Vue.js project using Vue CLI 3 and setting up the import statement with the @ alias, I encountered an error when running npm run build. Can you explain why this happened? Error Message $ npm run build > [email protected] build / ...

What could be causing React to generate an error when attempting to utilize my custom hook to retrieve data from Firebase using context?

Currently, I am restructuring my code to improve organization by moving data fetching to custom hooks instead of within the component file. However, I am encountering issues with the hook not functioning properly when used in conjunction with my context. ...

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

Exploring the use of national flag emojis in VS code

I've been attempting to use flag emojis as reactions on a Discord bot, but they just won't cooperate. Every time I try something like this > ':flag_jp:', I encounter the following error: Error: DiscordAPIError: Unknown Emoji EDIT ...

Exporting a module from a TypeScript definition file allows for seamless sharing

I am in the process of developing a definition file for the Vogels library, which serves as a wrapper for the AWS SDK and includes a property that exports the entire AWS SDK. declare module "vogels" { import AWS = require('aws-sdk'); export ...

How can I display the top 5 data results after subscribing in Nativescript?

Utilizing this function allows me to retrieve all my data from the web service. public data: Data[]; getall() { this.ws.getalldata().subscribe( data=> { this.data= data; } ); } Here is a ...

Implementing validation logic on button click using TypeScript

I'm struggling to get my validation to work for empty fields using the method below. Can anyone provide some guidance or suggestions? Thanks. Here is my template: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin ad ...

What is the best way to import a data type from another file into a `.d.ts` file without converting it into a module?

Recently encountered a peculiar scenario involving d.ts files and namespaces. I have some d.ts files where I define and merge a namespace called PROJECT. Take a look at how it's declared and automatically merged (across multiple files) below: file1 ...

The name 'XXX' is nowhere to be found

I encountered an error stating "Cannot find name 'Calendar Component'" while attempting to add a route to a component from another module in my app.module.ts file. Below is the content of my app.module.ts file: // Importing Modules // import {B ...

Enhancing Test Components with Providers in "React Testing Library": A Step-by-Step Guide

I am currently working with React-Testing-Library and have set up my main.tsx file with Redux-Toolkit and React-Router wrappers like this: ReactDOM.createRoot(document.getElementById("root")!).render( <React.StrictMode> <Provider s ...

Mixing Jest and Cypress in a TypeScript environment can lead to Assertion and JestMatchers issues

When utilizing [email protected] alongside Jest, we are encountering TypeScript errors related to Assertion and JestMatchers. What is the reason for these TypeScript errors when using Jest and [email protected] in the same project? ...

Using [file_id] as a dynamic parameter in nextjs pages

I am working with a nextjs-ts code in the pages/[file_id].tsx file. import Head from 'next/head'; import Script from 'next/script'; import Image from 'next/image'; import Link from 'next/link'; import { NextApiReques ...

Switch one button at a time within the form

I've been working on a form that includes email and communication channel options, and I'm trying to update the form and save the changes. However, I'm facing a problem with toggling the button/icon. Here's the code snippet: const [chec ...

Uncover the mystery behind the return value of a generic function in TypeScript

I can't seem to wrap my head around why TypeScript is behaving in the way described below. Snippet 01| const dictionary: { [key: string]: unknown} = {} 02| 03| function set<T>(key: string, value: T): void { 04| dictionary[key] = value; 05| } ...

Loop through every item in Typescript

I am currently working with the following data structure: product: { id: "id1", title: "ProductName 1", additionalDetails: { o1: { id: "pp1", label: "Text", content: [{ id: "ppp1", label: "Tetetet" ...

Dealing with Excessive Requests in a NextJS Application Routing Layout

Currently, I am developing a NextJS application with an app router that will feature a navigation component. Within this navigation, it is essential to display user information such as a username and avatar. I attempted to implement a layout file based on ...

Typescript types can inadvertently include unnecessary properties

It seems that when a class is used as a type, only keys of that class should be allowed. However, assigning [Symbol()], [String()], or [Number()] as property keys does not result in an error, allowing incorrect properties to be assigned. An even more curio ...

Having trouble utilizing yarn to import Mapbox into TypeScript

My process involves using the command: yarn add --dev @types/mapbox-gl @types/geojson This successfully adds mapbox and geojson to my project. I can see them when attempting to import mapboxgl. Next, I create something similar to this: import * as L ...