SQL Exception: The value for the first parameter is not defined

I'm encountering an issue with a SqlError while trying to retrieve data from my database. It seems like the problem is within my fetchData function where I might not be passing the two parameters (startDate and endDate) correctly.

The specific SqlError message that I am facing is:

SqlError: Parameter at position 1 is undefined

It's important to note that these parameters do contain values, as verified in my console:

start date: 2018-01-01 00:00:00
end date: 2022-08-15 00:00:00

Here is the implementation of my fetchData function along with some helper functions to track the state of startDate and endDate:

   const [startDate, setStartDate]: any = useState('');
   const [endDate, setEndDate]: any = useState('');

    //Retrieve data from the database
    useEffect(() => {
        fetchData();
    }, [startDate, endDate]);

    const fetchData: any = async () => {
        const response: any = await axios.get(`/api/get-canceled/${[startDate, endDate]}`);
        let dataRows: any[] = response.data;
        console.log('response', response.data);
        setRows(dataRows);
    };

  const handleStart = (e: any) => {
        const inputStart = e.target.value;
        setStartInput(inputStart);
        const start = `${inputStart} 00:00:00`;
        setStartDate(start);
    };
    console.log(startDate);

    const handleEnd = (e: any) => {
        const inputEnd = e.target.value;
        setEndInput(inputEnd);
        const end = `${inputEnd} 00:00:00`;
        setEndDate(end);
    };
    console.log(endDate);

This is how my API is configured:

import type { NextApiRequest, NextApiResponse } from 'next';
import * as pool from '../../../src/utils/dbConnection';
import console from 'console';

export default async (req: NextApiRequest, res: NextApiResponse) => {
    const { startDate, endDate }: any = req.query;
    let conn;
    try {
        conn = await pool.getConnection();
        const rows = await conn.query(
            `SELECT oi.po, oi.id, p.product_id, p.vendor_id, oi.quantity, oi.scanned_qty, oi.order_id, oi.qty_canceled, oi.channel_order_item_id, o.order_datetime, 
            o.ship_lastname, o.ship_firstname, o.ship_email, o.channel_order_id, o.channel_order_id_alt, o.channel_id, p.description, p.stock_status 
            FROM shopper s INNER JOIN orders o on s.id = o.shopper_id INNER JOIN orderitems oi ON o.id = oi.order_id INNER JOIN products p ON oi.item_id = p.id 
            WHERE o.order_datetime > ? AND o.order_datetime < ? AND oi.qty_canceled > 0;`,
            [startDate, endDate]
        );

        res.status(200).json(JSON.stringify(rows));
    } catch (err) {
        console.log(err);
    } finally {
        if (conn) conn.end(); // close connection
    }
};

Your assistance is highly valued. Thank you!

Answer №1

Consider updating the fetchData function in your front end code.

const updatedFetchData: any = async () => {
       const responseData: any = await axios.get(`/api/retrieve-canceled?start_date=${startDate}&end_date=${endDate}`);
       let fetchedRows: any[] = responseData.data;
       console.log('responseData', responseData.data);
       updateRows(fetchedRows);
};

Answer №2

It is recommended to utilize the params object in your axios get method calls.

axios.get('/api/get-canceled', { params : { startDate, endDate }});

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

Using TypeScript with React and Material-UI: Issue with undefined theme in createStyles()

Currently, I am delving into React with TypeScript and utilizing the Material UI framework for the frontend. In my quest to activate media queries, an error has crossed my path: Uncaught TypeError: Cannot read property 'up' of undefined ...

Next.js users have reported experiencing style flickering when utilizing material-ui's useMediaQuery feature upon initial rendering

Encountering style flickering on initial render in Next.js while using the @mui/material/useMediaQuery function. The issue arises from the useMediaQuery value changing between server side and client side rendering. Is there a solution to this problem? imp ...

Transferring data to a Component as properties in Next.js

I've encountered an issue while trying to pass editvalues as props to my EditForm component, resulting in the error 'editvalues is not defined'. Important note: editvalues is an object Upon using console.log(editvalues), I can see the valu ...

Dealing with soon-to-expire access tokens from a partner API

Just starting out with Next.js and facing a common challenge without knowing where to begin. Here's the scenario: I am working with a partner who has an API that requires Bearer authentication. The Bearer token is obtained by calling an endpoint (/au ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Passing a JSON object between pages in Next.js using props during programmatic navigation

In my Next.js project, I have two pages. On the first page, the user fills out a form to create a post. The information is stored in a large JSON object, which needs to be passed to the second page for the user to preview the post before finalizing it. Wi ...

What's the best way to replicate a specific effect across multiple fields using just a single eye button?

Hey everyone, I've been experimenting with creating an eye button effect. I was able to implement one with the following code: const [password, setPassword] = useState('') const [show, setShow] = useState(false) <RecoveryGroup> ...

What is the best way to verify that I am receiving the 'jwt' token in my code?

Trying to understand the data held by the jwt token in my next.js app, but encountering an error message saying error: jwt must be provided. Here's the code snippet causing the issue: import { NextRequest } from "next/server" ...

Tips for Simplifying Complex Switch Cases with Object Literals in TypeScript

I have a unique situation where I need to switch between two functions within an object literal. One function takes two numerical arguments, "A" and "B", while the other function only takes a single string argument, "C". My TypeScript code showcases my di ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

Can you explain how to utilize a function on a client component in Next.js?

I'm a bit lost on how client components function. I am working on an image uploader project where I need to extract the userId from supabase, utilize the supabase server function, and then upload the image to supabase storage with the "userId/filename ...

Dockerized NextJS and Strapi setup

I am currently facing challenges in containerizing a NextJS application along with a Strapi application using Docker. My project structure is as follows: /project /strapi ... Dockerfile /nextjs ... Dockerfile docker-compose.yml Ultimat ...

Adding custom CSS and JavaScript to an Angular 4 project can be done by including the necessary

When working with Angular 2, I was able to include stylesheets directly in the index.html like so: <link rel="stylesheet" href="css/mycss.css"> However, with Angular 4, the styles need to be added to the angular-cli.json file within the styles and ...

Unveiling the Ultimate Method to Package Angular 2 Application using SystemJS and SystemJS-Builder

I'm currently in the process of developing an application and I am faced with a challenge of optimizing the performance of Angular 2 by improving the loading speed of all the scripts. However, I have encountered an error that is hindering my progress: ...

Instructions for creating a function that can receive an array of objects containing a particular data type for the value associated with the key K

Seeking guidance on how to define a specific signature for a function that accepts an array of objects and 3 column names as input: function customFunction<T, K extends keyof T>( dataset: T[], propertyOne: K, propertyTwo: K, propertyThird: K ...

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

Angular Routing can be a powerful tool for managing multiple article posts in an efficient and organized way

I am in the process of building a website with Angular that features numerous articles. Whenever a user clicks on an article, I want it to navigate to a new URL using routing. To achieve this, I have created a new Article component and here is how my app- ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

Trouble with useEffect not triggering in NextJS 13.4 (app router) application

When trying to fetch data from the next API route, I encountered an issue where the useEffect method did not trigger on page reload. Additionally, I was unable to make this component async as Next.js does not allow async functions in client components. pa ...