Next.js, Knex, and SWR: Unusual issue disrupting queries

When making API requests using Next API routes and interacting with Knex + MySQL, along with utilizing React and SWR for data fetching, I encountered a strange issue. If a request fails, my SQL queries start to append ", *" to the "select" statement, causing SQL syntax errors. For instance, what should be a query like "select *", ends up as "select *, *" and then progresses to "select *, *, *" and so forth. Does anyone have any insights into why this could be happening?

Fetching data with SWR:

export const swrFetcher = async (...args) => {
  const [url, contentType = 'application/json'] = args;
  const res = await fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': contentType,
    },
  });
  if (!res.ok) throw new Error(res.statusText);
  const json = await res.json();
  return json;
};

const { data, error } = useSWR('/api/user/me', swrFetcher, {
    revalidateOnFocus: false,
    revalidateOnReconnect: false,
    revalidateOnMount: true,
  });

Knex query:

const User = knex(TABLE_NAMES.user);
export const readById = (id) => User.select('*').where({ id });

Answer №1

To better optimize your code, consider creating a new instance of the knex object within the function call instead of reusing the same instance each time.

export const readById = (id) => {
    const User = knex(TABLE_NAMES.user);
    return User.select('*').where({ id });
}

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

The most recent version of Autonumeric now permits the inclusion of a decimal point, even if the decimalPlaces parameter

I need to ensure that only whole numbers are allowed in the input textboxes, while also displaying a currency symbol and commas. I am using the most recent version of Autonumeric JS for this purpose. Even after setting the decimalPlaces property to 0, I a ...

Could someone kindly clarify the workings of this jQuery script for me?

I found this code online, but I'm struggling to comprehend its functionality. In order to make any edits for my needs, I need to understand how it operates. The purpose of this script is to close a panel with an upward slide animation when the "x" but ...

Is there a way to display the button just once in a map function while still retaining access to the iteration value?

Utilizing formik within material-ui for a form has been quite productive. I've implemented a map function to print text fields and managed to display the Submit button only once by targeting the index. However, there's an issue when attempting to ...

What is the best way to transform a JavaScript object into a JavaScript literal?

Currently, in my nodejs project, I have an object defined as follows: const objA = { key : 'value' }; My goal is to create a new file named obja.js which should contain the same literals from the object, rather than as a JSON literal. How can I ...

Choosing to maintain an open server connection instead of regularly requesting updates

Currently, I am in the process of developing an innovative online presentation tool. Let's dive into a hypothetical situation: Imagine one person is presenting while another connects to view this presentation. >> How can we ensure that the viewer&ap ...

The application runs smoothly during development, but encounters issues once deployed on Heroku

I am encountering an issue while deploying my app on Heroku. The deployment process goes smoothly, but when I try to open the app, I receive the following error message: Application error An error occurred in the application and your page could not be ser ...

Learn how Angular 2 allows you to easily add multiple classes using the [class.className] binding

One way to add a single class is by using this syntax: [class.loading-state]="loading" But what if you want to add multiple classes? For example, if loading is true, you want to add the classes "loading-state" and "my-class". Is there a way to achieve t ...

Anticipated the server's HTML to have a corresponding "a" tag within it

Recently encountering an error in my React and Next.js code, but struggling to pinpoint its origin. Expected server HTML to contain a matching "a" element within the component stack. "a" "p" "a" I suspect it may be originating from this section of my c ...

Using React Hooks to render radio buttons within a map iteration

My code contains a nested map function where I try to retrieve values from radio buttons. However, the issue is that it selects all radio buttons in a row instead of just one. Below is the snippet of my code: <TableHead> <TableRow> ...

When trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

Send a request to templateUrl

After experimenting with AngularJS, I decided to create a dynamic route system that funnels all routes through a single PHP file. This was motivated by my desire to prevent users from accessing raw templateUrl files and seeing unstyled partial pages. Prio ...

In Angular 2, you can include a routerLink in a child component that directs to the root

Currently, I am developing a web application using Angular 2 Beta 8 and encountering an issue with nested routes while utilizing the routerLink directive. The structure of the router is as follows: AppCmp |-> NewItemFormCmp |-> UserDashboardCmp ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...

Angular - Collaborative HTML format function

In my project, I have a function that sets the CSS class of an element dynamically. This function is used in different components where dynamic CSS needs to be applied. However, every time I make a change to the function, I have to update it in each compo ...

Using Laravel and AJAX to save multiple selected filters for future use

I've been struggling with this issue for a few weeks now and just can't seem to wrap my head around it. On my webpage, I've implemented four filters: a search filter, a year filter, a launch-site filter, and a country filter. Each of these ...

What is the maximum duration we can set for the Ajax timeout?

I am facing a situation where an ajax request can take between 5-10 minutes to process on the server side. Instead of continuously polling from JavaScript to check if the request is completed, I am considering making just one ajax call and setting the tim ...

JavaScript's "for of" loop is not supported in IE 11, causing it to fail

Here is a piece of code I'm using to select and remove a d3.js node: if (d.children) { for (var child of d.children) { if (child == node) { d.children = _.without(d.children, child); update(root); ...

Generate dynamic DIV elements and populate them with content

Can you assist me in getting this code to function properly? My goal is to dynamically create elements inside a div and fill each element with a value fetched from the database through a server-side function. I'm unsure if there's a better approa ...

Error message: When attempting to create dynamic inputs in React, an error occurs stating that instance.render is not

I encountered an issue while attempting to create dynamic inputs in React. The error message 'TypeError: instance.render is not a function' keeps popping up. import React, { Component } from 'react'; import Input from '../../Ui/Inp ...

Material UI - Exploring the Tree View Component

Seeking advice on structuring server data for utilization with the TreeView component from Material UI: https://material-ui.com/api/tree-view/ I need to efficiently handle large datasets by fetching child nodes dynamically from the server upon user intera ...