Unable to utilize console.log and alert functions within the Next.js application

I'm currently facing a problem in my Next.js application where the console.log and alert functions are not functioning as intended. Despite checking the code, browser settings, and environment thoroughly, pinpointing the root cause of the issue remains elusive. Here's an overview of the situation:

For debugging purposes, I employ console.log statements within my code. However, no output is visible in the developer console of the browser when these statements are included. Furthermore, the alert function fails to generate pop-up alerts as expected.

Node.js Version: 18.17.1 Next.js Version: 13.5.4 typescript": ^5

Errors and Warnings displayed in the browser's developer console:

invariant expected app router to be mounted

The following snippet showcases the most pertinent details (extracted for clarity):

\mooneducationcenter\src\app\addteam\page.tsx

"use client";

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

export default function AddTeam() {
  console.log("## This is console message ##");

  const [name, setName] = useState("");

  const router = useRouter();

  const handleSubmit = async (e:any) => {
    e.preventDefault();

    if (!name) {
      alert("Name is required.");
      return;
    }

    try {
      const res = await fetch("http://localhost:3001/api/teams", {
        method: "POST",
        headers: {
          "Content-type": "application/json",
        },
        body: JSON.stringify({ name }),
      });

      if (res.ok) {
        router.push("/");
      } else {
        throw new Error("Failed to create a team");
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-3">
      <input
        onChange={(e) => setName(e.target.value)}
        value={name}
        className="border border-slate-500 px-8 py-2"
        type="text"
        placeholder="Name"
      />
      
      <button
        type="submit"
        className="bg-green-600 font-bold text-white py-3 px-6 w-fit"
      >
        Add Member
      </button>
    </form>
  );
}
`

Various troubleshooting measures have been attempted, such as rebuilding the application and conducting tests in incognito mode; however, the issue persists. Interestingly, when the same code file was tested on another Next.js application within the same browser, the console.log and alert functions operated as anticipated.

A potential hypothesis is that the problem might stem from the project's configuration or dependencies. Thus, any guidance in identification and resolution of this issue would be immensely valued. Thank you.

Answer №1

Your program is functioning properly on my computer. However, when I attempt to click the "add member" button, an alert pops up stating that a name is required. After entering a name, it redirects me to a new page and displays console messages when I modify the model. If you encounter issues, consider changing your browser. Take a look at the central alert box and the console messages on the right side in the image below: https://i.stack.imgur.com/Br0zc.png

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

Is it possible to manipulate videos embedded in an iframe using javascript?

It's common knowledge that JavaScript commands from Google can be used to control YouTube videos, while Vimeo provides its own JavaScript commands for their videos. Both videos are typically embedded within 'iframes' on websites. I'm ...

Transitioning from jQuery to Prototype

After switching from a jQuery background to Prototype, I am curious if there is a chart available that shows the equivalent prototype methods for specific jQuery methods? To be more specific, I am searching for the equivalent of $('#my-id').prep ...

Filling an HTML template with an $http response in VueJS

After learning about VueJs, I decided to embark on a small project - a nutrition app where food recommendations are made based on specific nutrients. Below is the JavaScript code snippet: recommendFood: function() { this.recs = {}; ...

A guide on verifying if two arrays of integers are permutations using JavaScript

Is there a way to determine if two sets of integers in JavaScript are permutations? For example, given the arrays: a = [1, 2, 3, 4, 5] and b = [2, 3, 5, 1, 4] I want a function that will return true if they are permutations of each other. ...

Performing bulk operations on multiple documents in MongoDB by specifying a custom identifier for updating or

Recently, I've been working with a mongo schema const taskSchema=new Schema({ userID:{type:ObjectId,required:true}, task: { type: String, required: true, trim: true, maxlength: 30, }, finalDate:{type:Date,required:true}, ...

I am looking to optimize my JavaScript function so that the console.log structure is functioning correctly. What changes can I make to

I've been trying out this method to tackle the issue, however, my console.log isn't providing the expected output. What adjustments should I make? const executeCalculator = ({ x, y, operation }) => { let calculator = { x: this.x, ...

Prevent a React component from unnecessarily re-rendering after a property has been set

I am working on a react component that displays a streaming page similar to the one shown in this image. Here is a snippet of the code : const [currentStream, setCurrentStream] = useState<IStream>(); const [currentStreams] = useCollectionData<ISt ...

How can I access the data variables from a JSON request within a function?

My task involves loading multiple JSON files from an array called bunchOfData, with each file having a corresponding URL. How can I access my variable "myI" within the processData function? for(var i = 0; i < bunchOfData.length; i++){ $.getJS ...

Error Encountered: Angular 2 ngOnInit Method Being Executed Twice

Encountered an unusual error in Angular 2 while working on two components that share similarities in templates and services. Here is a breakdown of how they function: Component: data: any; constructor(private _service: TheService) {} ngOnInit() { t ...

Challenge with Transferring Data to be Displayed

My issue lies in calling a function with 3 inputs - 2 numbers and 1 string. The two numbers are being passed correctly, but I need the string to be printed within the element. I suspect the problem is related to passing the parameter to an HTML part of th ...

What are the advantages of polymer's inter-component data binding?

I am working on a login component and I want to ensure that the login status is accessible by other components within my application. Is there anyone who can share some functional code snippets or examples? I require a method for binding or event handlin ...

Is it possible to create an Excel add-in taskpane using ReactJS and NextJS?

Can NextJS be integrated with an Excel task pane in a ReactJS app? If it is possible, could you provide me with an example or guide me to any resources on the web? ...

Explore all potentialities within an array of objects by examining and contrasting their key values

Looking to run a specific math formula with three parameters using an array of objects in JavaScript. The scenario involves sports, where there are three possibilities: Team A (win), Team B (win), or Draw. There are three different bet websites offering o ...

Customize dynamically loaded data via AJAX

I have a webpage that is loading a table from another source. The CSS is working fine, but I am facing an issue editing the table using jQuery when it's loaded dynamically through a script. It seems like my changes are not getting applied because they ...

Guide on utilizing "setFont" in jsPDF with UTF-8 encoding?

Currently working on a project using Angular 7 I am trying to incorporate a custom font (UTF-8) into my PDF generation service using jsPDF. Despite researching various examples, none seem to work for me. The documentation on the jsPDF GitHub page mentions ...

Is it possible to create a collapse and expand animation that does not involve transitioning the `height

After extensively researching, I have come across numerous articles advocating for the use of transform and opacity for achieving smooth CSS transitions. An example can be found here: The prevailing notion always revolves around: ...the optimization ...

The error encountered is: "TypeError: req.flash does not exist as a function in NodeJs

When it comes to working with Registration on a Site, the Validation process is key. In this case, mongoose models are being used for validation and an attempt is being made to utilize Flash to showcase error messages within the Form. However, there seems ...

Tips for integrating AngularJS into Zend Framework 2

Hi there! I am a newcomer to Zend Framework 2 and I am exploring the integration of AngularJS into my project. Currently, I am calling a function in the controller like this: return new ViewModel(array( 'result' => $result, 'use ...

Tips for controlling the size of a canvas element: setting minimum and maximum width and height properties

function convertImageResolution(img) { var canvas = document.createElement("canvas"); if (img.width * img.height < 921600) { // Less than 480p canvas.width = 1920; canvas.height = 1080; } else if (img.width * img.he ...

Transform Ajax response into dropdown menu option

I have made an ajax call and received HTML as a response. Now, I need to convert this output into options and add them to select tags on my webpage. <div class="views-element-container"> <div class="view view-contact-view-id-conta ...