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

Issue with Next.js's notFound() function not properly setting the 404 HTTP Header

Our decision to use Nextjs was primarily driven by the need for SSR and SEO optimization. We rely on an external REST API to fetch data on the front end, but we face challenges when trying to pre-render certain pages and display a proper 404 Not Found head ...

"Next JS throws an error stating that 'window' is not defined

Need some assistance here. I've been attempting to implement react-wysiwyg-editor in my next js app, but keep encountering an error stating that 'window is undefined.' import React, { useState } from "react"; import { Editor } from ...

The dropdown div does not activate when the image is clicked

When the image in the simple dropdown is clicked, it fails to activate the dropdown feature. This issue was encountered while working on a Shopify project, making it challenging to troubleshoot. To demonstrate the problem, I have re-created the scenario i ...

I am having trouble getting Form.Select to work in my basic react-bootstrap application, despite following the guidelines provided in the react-bootstrap documentation. Can

I am new to utilizing "react-bootstrap with hooks" and currently in the process of creating a basic form. I have been following the guidance provided by react-bootstrap documentation, but I encountered an issue specifically with select/option form elements ...

Node.js module retriever showing as blank

My current challenge involves the creation of a settings class with one getter. Here is how it currently looks: class Configuration { get endpoint() { return 'https://api.example.com'; } } module.exports.Configuration = Configuration; In a ...

Combining JSON objects in a Pentaho JavaScript JSON by matching keys to merge with an existing JSON document

My goal is to construct a Json document by breaking it down into smaller pieces, with each piece containing the necessary keys to insert the smaller Json bits into the correct json structure. As I am relatively new to JavaScript and still in the process of ...

Navigate the orbit control camera in a circular motion around the target object

Just starting out in the world of threejs. I've managed to create a cube with different colors on each face. This cube can be rotated using OrbitControl, and I have 6 buttons in Dat.GUI that control the camera position. My goal is to click "Animate t ...

When attempting to use Arabic characters in my PDF file with LIP, I encounter an error: "TypeError: font must be of type PDFFont or n, but was actually of type NaN"

all I am facing an issue with Arabic characters when trying to use different fonts in my project. I have attempted to encode the Arabic letters using various npm packages, but I keep receiving a TypeError: font must be of type PDFFont or n but was actuall ...

The preflight styles in twin.macro have their own unique design that sets them apart from those in

After conducting research on the twin.examples repository for Next.js, I discovered that twin.macro suggests integrating their preflight component, which they refer to as <GlobalStyles />. Often, it is aliased as <BaseStyles />, as this compone ...

Enhance the color scheme of your collapsed or expanded Bootstrap NAV for mobile devices

Currently working on customizing the navbar using Bootstrap. I've been able to style it perfectly for both desktop and mobile devices in its initial state. The issue arises when attempting to style the navbar in its expanded and collapsed states on m ...

The dilemma of selecting objects in Three.js

Currently, I am developing a small web application that utilizes three.js. However, I have encountered an issue: I created a prototype with my three.js content and everything functions correctly (the canvas size in the prototype matches the browser window ...

I successfully merged two arrays (decks of cards) without using recursion, but I'm curious to understand where I went wrong with the recursive approach

Currently, I am working on a function that shuffles two arrays together using recursion. The goal is to combine the top and bottom halves of a deck of cards into a single array with elements interleaved. For example: The first element should come from the ...

Setting the className in Next.js without using {styles.red} can be achieved by directly passing the

Description I'm trying to use just the pure class name without the {styles.class-name} convention in Next.js. After doing some research, I discovered that I need to configure the next.config.js file. Does anyone have good references for this? Current ...

What is the best way to incorporate a range of details into a div using only jQuery, all while avoiding the use of data-

I'm struggling to find a concise way to explain this, so please bear with me. The information I'm sharing here is all just for example purposes and may sound strange. I have been working on creating a character select page where clicking on a cha ...

Material UI offers a feature that allows for the grouping and auto-completion sorting

I am currently utilizing Material UI Autocomplete along with React to create a grouped autocomplete dropdown feature. Here is the dataset: let top100Films = [ { title: "The Shawshank Redemption", genre: "thriller" }, { title: " ...

Passing parameters to JavaScript onload event from PHP

Looking for help with integrating date data from PHP into a JavaScript countdown function. I have extracted the date from a database using PHP, but struggling to pass it correctly to the JavaScript function. My attempt so far: <body onload="countIt(< ...

CSS classes designed to mimic JavaScript object attribute-value pairs

I stumbled upon some interesting css class-value combinations within HTML tags. It seems like a specific JavaScript code is interpreting this, but it's something I haven't encountered before. I came across this on www.woothemes.com/flexslider/ (y ...

Having trouble getting the NextJS custom 404 page to display?

I've located the 404.tsx file in the apps/specificapp/pages/ directory, yet NextJS continues to show the default pre-generated 404 page. Could there be a misunderstanding on my part regarding the documentation, or is there some obstacle preventing me ...

Guidelines for implementing a conditional if-else statement in a props-based Next.js component

I have a Card component, and I would like to implement a condition where if the data is equal to 0, it should display the first image, otherwise it should display the second image. Here's more information: {data?.data?.map((dataVote: any, i: numbe ...

As the page is resized or zoomed in and out, the div elements start shifting in different directions

When I apply position:absolute to prevent the elements from moving when zooming in and out of the page, they all end up congregating in one place. Can anyone help me with this issue? None of the solutions I've found have worked so far. I'm develo ...