The useRouter() function doesn't seem to be successfully navigating to the main landing page

"use client"
import { useState } from 'react';
import {auth} from '../../firebase-config'
import {createUserWithEmailAndPassword} from 'firebase/auth'
import { useRouter } from 'next/router';
const SignUp = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const handleSubmit = (e) => {
       const router = useRouter();
        
        e.preventDefault();
        // Handle form submission here (e.g., send data to server)
        createUserWithEmailAndPassword(auth , email,password)
        .then(()=>{
            setEmail('');
            setPassword('');
            router.push('/')
        }).catch((err)=>{
            throw console.log(err);
        })
    }

I have tried various methods like using useEffect hook and windows.location.href, but I am still facing issues with redirecting the user to the landing page after submission. I even restarted my server, but nothing seems to work as expected.

Answer №1

The current implementation you have includes the useRouter() hook being called within the handleSubmit function, which may be causing routing issues. In Next.js, it is important to remember that hooks should be called at the top level of your component and not inside any nested functions or callbacks.

const SignUp = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const router = useRouter();

    const handleSubmit = (e) => {
       ...
    }
...

Answer №2

For optimal usage, it is recommended to move the line const router = useRouter(); right after importing it. This will ensure that router is accessible at the top level instead of being restricted inside the SignUp function.

"use client"
import { useState } from 'react';
import {auth} from '../../firebase-config'
import {createUserWithEmailAndPassword} from 'firebase/auth'
import { useRouter } from 'next/router';
const router = useRouter();
const SignUp = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const handleSubmit = (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

Incorporate time zone awareness to JavaScript date objects

Whenever I create objects in my MongoDB using Mongoose, the dates are displayed in the format of, for example, 2016-10-10T15:35:52.764Z (alternatively, it could be yyyy-MM-ddTHH:mm:ssZ). When I utilize Date.now() in JavaScript, I am given a timestamp. Is ...

Create a URL hyperlink using javascript

I am looking to create a link to a page that updates its URL daily. The main URL is where X represents the day of the month. For example, for today, July 20th, the link should read: In my JavaScript section, I currently have code that retrieves the cur ...

How to access a particular tab in Bootstrap 5 using an external link

Is there a way to direct users to a specific tab upon clicking a link on another page? Check out the example below: <div class="products-btn"> <a href="products.html#pills-profile">view all</a> </div> On Pro ...

Connecting registered users to a database in a Firebase web application

What is the best way to connect authenticated users to my Firebase database within my Angular JS web application? I have already created a "users" node in my database tree to store user data, but I am struggling with how to organize each user's infor ...

Achieve this effect by making sure that when a user scrolls on their browser, 50% of the content is entered into view and the remaining 50%

Is there a way to achieve this effect? Specifically, when the user scrolls in the browser, 50% of the content is displayed at the top and the other 50% is shown at the bottom. ...

Addressing the issue of Google Charts legends overlapping

As a newcomer to Stackoverflow and Google Charts, I am encountering an issue in one of my projects that utilizes the Google Charts API. Specifically, I am trying to display two legends on the chart but they are overlapping in the preview. Despite explorin ...

Execute JavaScript using "matches" without the need for the page to refresh

I have been developing a school project which involves creating a Chrome extension to streamline the Checkout process on a website. In my manifest.json file, I specified that a content.js file should run when it matches a specific URL. "content_script ...

Initializing JavaScript prior to registering the Polymer element

When upgrading from Polymer version v0.5 to v1.0, the process of registering Polymer elements seems to have changed. Previously, in Polymer v1.0, we were able to execute JavaScript code from the index.html file to initialize all the necessary objects in ou ...

Unable to locate a contact within the state

Currently, I am diving into the world of React by exploring its documentation and challenging myself to build a small chat application. While I have a good grasp on the basics, I am encountering some issues with states. Within my code, there is an object ...

Which data types in JavaScript have a built-in toString() method?

Positives: 'world'.toString() // "world" const example = {} example.toString() // "[object Object]" Negatives: true.toString() // throws TypeError false.toString() // throws TypeError Do you know of any other data types that wi ...

Implementing an automatic link generation feature for files within a directory using JavaScript

I could really use some assistance with this. I created a YouTube example, which can be viewed in this PLNKR LINK: http://plnkr.co/edit/44EQKSjP3Gl566wczKL6?p=preview In my folder named embed, I have files titled p9zdCra9gCE and QrMOu4GU3uU, as shown belo ...

Dealing with Laravel and AJAX - Issue with Loading DIV

I find myself in a perplexing situation. Despite not encountering any errors in my apache logs or browser (chrome), I am faced with an issue that has left me baffled. On a specific page (localhost/admin/networks), I can click on an item from a database-ge ...

Eliminating Tailwind typography with PurgeCSS in a next.js project

Building a next.js site and utilizing specific text like the code snippet below: const defaultTheme = require('tailwindcss/defaultTheme') module.exports = { theme: { extend: { fontFamily: { sans: ['SFMono-Regular', ...

How come I am unable to expand a collection of objects using Zustand?

I am currently utilizing Zustand in a TypeScript Next.js application. Strangely, whenever I attempt to loop through my state object, I encounter a runtime error message. The structure of the damaged zone object for my car is as follows: const damagedZones ...

Creating a personalized image download feature in PhotoSwipe.js

I am currently working on a project that involves using the PhotoSwipe gallery. At line 175, there is code url:items[0].hqImage. I want to use the index of the current image instead of 0. How can I achieve this? I attempted to utilize the pswp.listen(&ap ...

Awaiting the completion of multiple asynchronous function executions

I am currently working on a promise function that executes an async function multiple times in a loop for different data. I would like to ensure that all async functions are completed before resolving the promise or calling a callback function within a non ...

Fetching content and an image simultaneously via AJAX

My website features a photo gallery that I created using the code below: /*Begin Photo Gallery Code*/ var images = ['g1.jpg', 'g2.jpg', 'g3.jpg', 'g4.jpg']; function loadImage(src) { ...

Transferring information between different parts of a system

I have created a component that includes a state called chosenGenre, along with a function that updates this state based on button clicks. My goal is to access the updated state (which is of type string) in another component. This is the initial componen ...

TypeScript Error: The Object prototype must be an Object or null, it cannot be undefined

Just recently, I delved into TypeScript and attempted to convert a JavaScript code to TypeScript while incorporating more object-oriented features. However, I encountered an issue when trying to execute it with cmd using the ns-node command. private usern ...

Quicker Solution to Iteration in Google Apps Script with JavaScript

I've set up a for loop to extract sales data from an array (salesLog) and transfer it to a designated sheet (targetSheet) in columns. The sales data is spread across multiple columns in the array. The loop adds up the columns between columnStart and c ...