Error encountered: TypeScript type error in my server-side action in Next.js

Currently seeking assistance with a server action in my Next.js application. I am encountering a type error that I can't seem to identify the root cause of. This issue arises when there are three values being passed into db.insert for orderProduct, and it consistently errors out on the first value regardless of the field.

File: create-order.tsx

products.map(async ({ productId, quantity, variantId }) => {
  await db.insert(orderProduct).values({
    productVariantId: variantId,
    productId: productId,
    quantity,
    orderId: order[0].id,
  })
})

Schema:

export const orderProduct = pgTable('order_product', {
  id: serial('id').primaryKey(),
  quantity: integer('quantity').notNull(),
  productVariantId: serial('productVariantId')
    .notNull()
    .references(() => productVariants.id, { onDelete: 'cascade' }),
  productId: serial('productId')
    .notNull()
    .references(() => products.id, { onDelete: 'cascade' }),
  orderId: serial('orderId')
    .notNull()
    .references(() => orders.id, { onDelete: 'cascade' }),
})

Types:

import * as z from 'zod'

export const createOrderSchema = z.object({
  total: z.number(),
  status: z.string(),
  paymentIntentId: z.string(),
  products: z.array(
    z.object({
      quantity: z.number(),
      productId: z.string(),
      variantId: z.string(),
    }),
  ),
})

Error Message:

No overload matches this call.
  Overload 2 of 2, '(values: { quantity: number | SQL<unknown> | Placeholder<string, any>; id?: number | SQL<unknown> | Placeholder<string, any> | undefined; productId?: number | SQL<...> | Placeholder<...> | undefined; productVariantId?: number | ... 2 more ... | undefined; orderId?: number | ... 2 more ... | undefined; }[]): PgInsertBase<...>', gave the following error.
    Object literal may only specify known properties, and 'productVariantId' does not exist in type '{ quantity: number | SQL<unknown> | Placeholder<string, any>; id?: number | SQL<unknown> | Placeholder<string, any> | undefined; productId?: number | SQL<...> | Placeholder<...> | undefined; productVariantId?: number | ... 2 more ... | undefined; orderId?: number | ... 2 more ... | undefined; }[]'.ts(2769)

I continue to receive this error even if I rearrange the values within my db.insert function.

Answer №1

After some investigation, I have discovered the solution. In my code, instead of using z.string() for the productId and variantId, it should be z.number()

import * as z from 'zod'

export const createOrderSchema = z.object({
  total: z.number(),
  status: z.string(),
  paymentIntentId: z.string(),
  products: z.array(
    z.object({
      quantity: z.number(),
      productId: z.number(),
      variantId: z.number(),
    }),
  ),
})

Answer №2

Implementing Modular Design:

  • To maintain consistency and accuracy, it is important to establish base schemas such as DbProductSchema and DbOrderSchema.
  • Customize schemas for specific use cases by utilizing methods like extend, pick, or omit.

Following Schema Naming Conventions:

  • Add a prefix of "Db" to base schemas that mirror database structures (e.g., DbProductSchema).
  • Consider descriptive names like create, read, update, or basic for operation schemas.

order-product.schema.ts

import * as z from 'zod';

// Establishing the base schema for products to ensure uniformity in operations.
const DbProductOrderSchema = z.object({
  productId: z.number(),
  quantity: z.number(),
  variantId: z.number(),
});

// Defining specific schemas for product operations like creation and reading.
export const OrderProductSchema = {
  create: DbProductOrderSchema,
  read: DbProductOrderSchema.extend({
    id: z.string().uuid(), // Adding a unique ID for identification
  }),
};

order.schema.ts

import * as z from 'zod';
import { OrderProductSchema } from './order-product.schema'; // Importing product schema for reusability

// Building the base schema for order data, including products using the basic ProductSchema.
const DbOrderSchema = z.object({
  total: z.number(),
  status: z.string(),
  paymentIntentId: z.string(),
  orderDate: z.date(),
  products: z.array(OrderProductSchema.create), // Ensuring products adhere to the basic schema
});

// Defining specific schemas for order operations like creation and reading.
export const OrderSchema = {
  create: DbOrderSchema.omit({ orderDate: true }).extend({
    orderDate: z.coerce.date(), // Coercing string to date format
  }), // Designed for creating new orders
  read: DbOrderSchema.extend({
    id: z.string().uuid(), // Including a unique ID for order identification
  }),
};

This approach will streamline project management tasks. An example for handling dates has been provided; similarly, you can incorporate product schemas as needed.

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

Extending a module in a TypeScript definition file

After examining this definition file, it seems that extending the exported Request interface is not possible due to the namespace not being exported. If anyone has any insights or suggestions on how to achieve this, I would greatly appreciate it :) I made ...

Having trouble with Next-auth integration, MongoDB database, and AWS SES functionality not functioning correctly

I am looking to implement next-auth with a passwordless email provider for my login page, utilizing MongoDB to store user data. Additionally, I plan to use AWS SES for email sending. Here is the current status of my project: I have set up a basic Next.js ...

Obtain precise JSON information using Node.js

Having limited experience with Angular JS and Node JS, I find myself in need of assistance. On the server side, I have multiple JSON files containing language translations. Based on a client's request for a specific language, such as French, I must re ...

What is preventing me from retrieving the data stored in my JSON?

My PHP code snippet involves checking if POST data is not empty and the action is 'edit'. If this condition is met, it fetches data from the database based on the selected IDs and prepares a JSON response. if(!empty($_POST)&&($_POST[&apo ...

Issue with Angular and CharJS: TypeError occurs when trying to read property '15' of an undefined value

An error message was encountered as follows: ERROR TypeError: Cannot read property '15' of undefined at ChartElement.getPixelForValue (Chart.js:14599) at ChartElement.updateElement (Chart.js:5930) at ChartElement.addElementAndReset (Chart.js:3781 ...

What is the best way to smoothly transition an element into view, then make it disappear seamlessly by fading it

Issue My current code features a <button> that, upon a single click, updates the class of a <div> element to "fade-in" and inserts it into the DOM. This action causes the <div> to visually fade in once it's in the DOM. However, if I ...

How do I maintain line breaks while using ajax to post a message via a url?

Check out this snippet of JavaScript and AJAX on another page: var req = getXmlHttpRequestObject(); function AddData(Data){ if (req.readyState == 4 || req.readyState == 0) { req.open("GET", '/getData.php?data=' + Data + '&&a ...

Adjust the zoom level when a location is detected using Mapbox

I have been reading through the leaflet documentation and it mentions using the maxZoom option for location, but I am having trouble getting it to work (http://leafletjs.com/reference.html#map-locate-options). Whenever a user uses geolocation on my websi ...

Find the item that has a specific value in its sub-property

Information Models: public class Header{ public int Identifier; public int value; public bool anotherValue; public List<Trailer> trailers; } public class Trailer{ public int ID; public Language MyLanguage; public string ...

Error message from @firebase/database: The Firebase Database URL could not be identified. Please ensure that you provide a Project ID when initializing firebase.initializeApp(). This issue is specific

Currently, I am in the process of setting up a live chatroom. Initially, everything was working perfectly on my first attempt. However, when I had to focus on another task and returned to this project, I encountered an error message stating that I cannot i ...

The assets path is the directory within the installed package that houses the main application files following the completion of a

I have a Vue.js UI component that is internally built using webpack. This reusable UI component library references its images as shown below: <img src="./assets/logo.png"/> <img src="./assets/edit-icon.svg"/>   <i ...

The Bootstrap 4 modal appears to be failing to load properly, as it is only

Trying to trigger a Bootstrap modal with a button click. Currently, there is one functioning modal on the page that works fine. However, when attempting to load another modal on a button click, only a faded screen appears. <button class="btn btn-green ...

How to turn off JavaScript using Selenium WebDriver?

Recently, I encountered a problem with my program that tests some of our sites with javascript disabled. Everything was working perfectly until we upgraded from WebDriver 2.4.5 to the latest version. Now, I'm faced with this error message: java.lang. ...

The JavaScript array created from parsing JSON returns a value of undefined

Once again, the gecko scenario! The JSON used in this script to fill a listbox has been validated by JSONLint. The code snippet below demonstrates how the parsed data is placed in arrays: pdata = jQuery.parseJSON(data); ctype = pdata[0]; stype = pdata[1]; ...

Exploring the World of AJAX with CodeIgniter

I've been on the hunt for a solid working example of using AJAX with Codeigniter, but most resources I've found are outdated. As an AJAX beginner, I'm struggling to find up-to-date tutorials. What I'm aiming for is an input form on a w ...

Tips on utilizing normalizr to flatten an array with various object types?

Upon receiving a JSON response from the server, it typically looks something like this: { data: [ { id: 1, type: 'person', emails: [ { id: 1 }, { id: 3 } ], phones: [] }, { id: 2, type: 'person', emails: [ { id: 2 } ], p ...

Steps for displaying an HTML table in Excel by clicking on a button

My goal is to open an HTML table in XLS format with a single click of a button. Currently, I have a JavaScript function that allows me to export the HTML table to XLS using the "save as" option. However, I want to enhance this functionality so that clickin ...

Show a collection of titles for unique post types

I am currently showcasing a custom list of post types using the following code: <!-- Displaying post type list --> <?php $args = array( 'post_type'=>'artworks_post', 'title_li'=> __(&apo ...

What is an alternative method to trigger a Bootstrap modal without using jQuery or bootstrap.js JavaScript code?

I am currently developing a survey application that is designed to be extremely lightweight. This application is specifically tailored for use in third world countries where internet connection is very limited. After conducting some research, we discovere ...

What are the steps to execute a module designed for NodeJS v6 LTS ES2015 in Meteor 1.4.x?

While I understand that Meteor includes NodeJS as a dependency, I'm facing an issue with a module written in ES6 that has a default argument value set within one of the Class methods. The problem arises when using Meteor v1.4.3.2: (STDERR) packages/m ...