Attempting to develop a server component that will transmit a JSON result set from a MySQL database located on the local server. What is the best method to send the server object (RowDataPacket) to the

After successfully rendering server-side pages and creating forms with react hooks for database updates, I encountered a challenge in integrating Ag-Grid into my application. Despite being able to retrieve data from the database using the mysql2 module and having it rendered in json format, I faced issues when attempting to pass this data to the client side (ag-grid) resulting in 'type' violations. My experience with Typescript has been challenging, but I am determined to overcome these obstacles.

I discovered that mysql provides two packet objects - a RowDataPacket containing the result set data in preformatted json, and a FieldPacket containing the column DDL of the result set. To streamline the process, I plan to create an api endpoint to serve the json data to the client side where I will utilize react hooks such as useState and useEffect to populate the ag-grid on the client-side. While this approach seems straightforward, I have encountered difficulties without the use of tools like Express, Axios, Prisma, or Vercel.

One potential solution could involve restructuring the received json data into a more usable format before serving it through the api. However, this method may require excessive effort and manipulation, potentially overloading the server. Despite exploring various discussions on the topic, finding a definitive answer has proved elusive thus far.

Any assistance or guidance on this matter would be greatly appreciated.

The Big Picture

Answer №1

Wow! It was surprisingly easy to figure out the issue. It had nothing to do with JSON data conversion from mySQL or Typescript, but everything to do with NextJS automatic routing. I've been focused on front-end development for so long that I overlooked the fact that automatic HTTP routes require a 'router.ts/js[x]' page instead of a 'page.ts/js[x]' page.

NextJS 14 is truly amazing!

Project structure plays a vital role: check out the server routes here

and view the FULL route.tsx code below:

import { pool } from "@/config/db.config";
import { NextResponse } from "next/server";

export async function GET() {
  let query: string = "SELECT * FROM product";

  try {
    const connection = await pool.getConnection();
    const [ rows, fields ] = await connection.query(query);

    connection.release();

    return NextResponse.json(rows);

  } catch (error) {
    console.error("Failed query: ", error);
    throw error;
  }
}

One important thing to note: ensure that the route handler is a valid HTTP Request type - in this case GET().

That's all for now.

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

An issue occurred with the DOMException while trying to execute the 'setAttribute' function on the 'Element': '{{' is an invalid attribute identifier

Currently, the code is under development and some methods are still empty while the *ngIf directives may not be correct in terms of logic. However, even with these issues, I encountered the same error without bothering to remove them at this stage. While ...

Troubleshooting the onExited callback issue with Popover component in Material UI

<Popover key={element.name} classes={{ paper: classes.paper }} open={open} anchorEl={this.myRef.current} anchorOrigin={{ vertical: ' ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

Exploring the capabilities of Angular 4 with the integration of the Web

Trying to integrate the Web Speech API Interfaces (https://github.com/mdn/web-speech-api/) with an Angular application (version 4.25) and an ASP Core web server. The project is built using Visual Studio 2017 (version 15.7.1). Added @types/webspeechapi type ...

Importing local JSON files into Vuex state

I am looking to import data from a local JSON file into a state value setting within my Vue.js application. store/index.js import { createStore} from 'vuex' export default createStore({ state: { settings: {} } }) assets/json/settings.j ...

Setting the root position of a div: How can it be done?

Imagine a scenario where a div element is designed to follow the mouse cursor on the screen. This functionality is achieved by manipulating the document's `mousemove` event and adjusting the div's `left` and `top` positions based on the event dat ...

I'm curious if there is a comparable method to achieve the functionality of MySQL's JSONOBJECTAGG() in MariaDB?

After experiencing a server crash while working on a data project, I am now in the process of recreating the database. Previously, I was using MySQL but now I find myself using MariaDB for the first time. In my previous work, I used a command to insert da ...

Exploring the integration of methods in Vue.js components

Within my Vuejs project, I developed a new form component and integrated it into the main index component. This new component needs to validate certain fields, with validation methods already created in the parent component. However, I am facing difficulti ...

Rails: Ensure that JSON form fields remain populated in case the form encounters a validation error

I am using a rails simple form to create a product with three fields inside in order to associate it with appropriate categories: <div class="form-group"> <%= f.input :child_category_id, :collection => @categories.order(:name), :l ...

Error: The property you are trying to set is undefined and cannot

When I attempt to set a property 'error' that is undefined, I receive a TypeError. The problematic line of code looks like this: this.error = error.code; This issue arises in an Angular Reactive Form while making a call to a web service. Below i ...

switch out javaScript for selenium

I'm attempting to replace the JavaScript functionality of a web page using Selenium (in Java with Firefox Geckodriver, if that makes a difference). Consider this webpage: <HTML><HEAD></HEAD> <BODY> <DIV id="time">Ti ...

How can React TypeScript bind an array to routes effectively?

In my project, I am using the standard VisualStudio 2017 ASP.NET Core 2.0 React Template. There is a class Home included in the template: import { RouteComponentProps } from 'react-router'; export class Home extends React.Component<Rout ...

What could be causing my component library styles to appear duplicated in Next.js?

I am currently working on a project that utilizes a component library where all components need to be wrapped in a <Theme> component. I have decided to place this component in the root layout file of my Next.js app, as it seemed like the most suitabl ...

"Concealing a column in a PrimeNG data table with dynamic columns: A step-by-step

Hi, I'm looking for a way to hide a column in my PrimeNG data table. Is there an attribute that can be used to turn off columns in PrimeNG data tables? .Html <p-dataTable emptyMessage="{{tbldatamsg}}" [value]="dataset" scrollable="true" [style]=" ...

Matching a regular expression pattern at the beginning of a line for grouping strings

One of my tasks involves working with a markdown string that looks like this: var str = " # Title here Some body of text ## A subtitle ##There may be no space after the title hashtags Another body of text with a Twitter #hashtag in it"; My goal ...

Top recommendations for Backand on JSON manipulation and associated entities

I am currently exploring how to set up my Backand application and its REST API. This question pertains to the topic of "Backand deep querying". I am in search of some best practice code examples for executing server-side code that loops through data object ...

Encountering the React Native error message "TypeError: Object(...) is not a function" while using react navigation stack

I am currently facing an issue with my react-navigation-stack. My suspicion lies in the dependencies, but I am uncertain whether that is the root cause. The objective at hand is to create a text redirecting to another page. If there is any irrelevant code, ...

EasyWaySaveArchive in ninja training - mastering the art of retrieving components

Recently started learning about dojo and JavaScript in general. I am currently working on a code snippet that requires a button to change based on the result of a php database query. The PHP script is already complete, and the code I am using so far looks ...

Updating the value of a rails parameter with JavaScript

I am trying to enhance my search form by pre-populating the fields with the "last searched values" when a user submits a search. The search form and results are displayed on the same page, and if there is no previous search, the fields should show placehol ...

The error message "Property 'DecalGeometry' is not found in the type 'typeof "..node_modules/@types/three/index"'."

Within my Angular6 application, I am utilizing 'three.js' and 'three-decal-geometry'. Here is a snippet of the necessary imports: import * as THREE from 'three'; import * as OBJLoader from 'three-obj-loader'; import ...