Having trouble with Next.js Error: Attempting to access undefined properties (specifically 'call') and can't resolve it with try/catch method when using onClick event?

var mysql = require("mysql");
import React from "react";

export async function executeMySqlQuery(myQuery) {
  try {
    console.log("Running query...");

    var connection = mysql.createConnection({
      host: process.env.MYSQL_HOST,
      user: process.env.MYSQL_USERNAME,
      password: process.env.MYSQL_PASSWORD,
      database: process.env.MYSQL_DATABASE,
    });

    connection.connect();

    connection.query(myQuery, function (error, results) {
      if (error) throw error;
      const output = results[0].solution;
      console.log(output);
    });

    connection.end();
  } catch (e) {
    console.error(e.message); // or "throw Error(e.message)", this shows it directly on top of the webpage
  }
}

The button I use to trigger the function (without the () => Next.js thinks it's an object)

<button onClick={() => executeMySqlQuery("SELECT 1 + 190 / 2 AS solution;")}> Execute SQL Query </button>

I also attempted this

<button onClick={async () => await executeMySqlQuery("SELECT 1 + 190 / 2 AS solution;") } > Execute SQL Query </button>

I encounter the following error:

Uncaught (in promise) Error: Cannot read properties of undefined (reading 'call')

This is the error in the DevTools console: https://i.sstatic.net/infN3.png

This is the error in Next.js, when I use throw Error(). https://i.sstatic.net/8m8TZ.png

Answer №1

An issue is occurring in the code enclosed within the try block, resulting in an error that is being handled in the catch block.

If you are working with the mysql Node.js package, please note that it is not compatible with client-side operations in the browser. To resolve this, consider moving the functionality to the backend or an API endpoint, and then sending requests from the client-side accordingly.

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

When performing an Angular HTTP post, additional parameters are automatically included in the request

Within a directive, I have the following code block: scope.progressCourse = -> req_data = course_id: scope.course.id success: true $http.post( "<%= Rails.application.routes.url_helpers.progress_course_path %>", req_data ).t ...

Is it possible to utilize fetch from the local drive in conjunction with App Router in the latest version of Next JS?

I encountered a 404 error and realized that the expected response from an on message listener had gone out of scope. Initially, I was working on creating an API for user authentication and was advised to convert it to route.js. So, I made the necessary ch ...

Form input using the div element (when clicked)

I am currently working on a page that connects to a database with user information. For each user, I am creating a separate div element so that there are 6 divs total (each representing a different user). My goal is to have the ability for a user to click ...

Juggling numerous pages in a React application

Our application is primarily flask/python based, with flask handling everything from user sessions to URLs. We are currently in the process of developing a UI component for our application using reactjs. We have successfully built the react bundle (bundle ...

Retrieving JSON data from a PHP file through a standalone JavaScript script

I am in need of creating a JavaScript file that will assign values to two variables within a PHP file. The PHP file should then construct a JSON structure and display some data. My goal is to have a form written in JavaScript with two input fields that wi ...

Updating data in React Native fails to activate useEffect, leading to the screen not being refreshed

I'm facing a challenge while working on a recipes app using Firebase Realtime database. I have a functional prototype, but I am encountering an issue where the useEffect hook does not trigger a reload after editing the array [presentIngredients]. Her ...

Guide to using the PUT method in Node.js Express to update a record using the primary key

I'm currently struggling with understanding the proper usage of the put statement in node js. Here is the code I have been using: app.put("/cars/:id", (req, res) => { //retrieving a record based on id (uuid) e.g. http://localhost:3000/cars/a5ad957 ...

What is the process for placing API routes within the new app directory of Next.js?

If you have a test API located at: pages\api\accounts\login.js, and are currently exploring the new app folder, which is still in its experimental phase in Next.js (as of today). Are you wondering if it's feasible to transfer your logi ...

Velocity: The initial parameter was not recognized as a property mapping

I've been experimenting with Velocity for animations (without jQuery), but I'm running into an issue where I keep getting this error message: Velocity: First argument ([object HTMLDivElement]) was not a property map, a known action, or a regis ...

Running JavaScript within Electron is a straightforward process

Looking to create an Electron application that can take code entered into a text area, execute it, and display the result. Any advice on converting the text to JavaScript and running it? ...

Remove nested comments using Ajax

I'm encountering a problem while attempting to delete my comments using Ajax. I believe I am on the right track but could use some guidance. Still in the process of familiarizing myself with jquery and similar technologies. While I can remove the comm ...

In my Cypress test for a new Next.js 13 app directory, I am looking to mock the session object for the api/auth/session route in NextAuth. Can you provide guidance

I have recently upgraded to the latest version of Next.js, which is 13, and I am now utilizing next-auth for authentication. The challenge I am facing is that the session is generated server-side, making it inaccessible in Cypress testing. My goal is to mo ...

Use joi to validate the entire request object

In order to ensure the validity of request input before calling the controller logic, I developed a middleware for that purpose. Let's suppose we have a route for "getting user by id". const usersController = require('../controllers/users.js&ap ...

Tips on how to send Mongoose response variable in NodeJS Express router res.render?

I just finished setting up a basic Express NodeJS server. My goal is to save the value of the setting returned from mongoose.find() as a variable in res.render, but every time I try, it throws an error saying Cannot read property of undefined. Here' ...

Unable to view videos shared by users in PeerJS and WebRTC video chat application from different tabs

Recently, I embarked on the task of creating a Video chat Website using Peer Js. Initially, everything seemed to be working fine as I was able to see my own video stream. However, a problem arose when attempting to view the video stream from another tab or ...

Utilize Vue to condense cells within a table

I am attempting to create a schedule table using vue.js. Each row represents an activity (in this example, only one is hardcoded), and each column represents a time period. The cells contain the names of users if they are scheduled during that time. https ...

Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format: text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] m ...

Locate a button element and dynamically assign an identifier using jQuery or JavaScript

I am currently working on a webpage that contains two forms, both enclosed within a <DL> element. <dl> <form action="" method="POST" style="display:inline-block;"> <dl><dt></dt><dd><input class="submit" typ ...

Steps for eliminating QRcode warning in npmjs package

Issue: Warning Message (node:24688) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) Seeking Solution: How can I prevent this warning ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...