Unable to submit form when button is clicked in Next.js/Typescript

"use client";

import { Product, Image, Color, Category, Size } from "@prisma/client";

// Remaining imports not included for brevity

const formSchema = z.object({
  name: z.string().min(1),
  image: z.object({ url: z.string() }).array(),
  price: z.coerce.number().min(1),
  categoryId: z.string().min(1),
  colorId: z.string().min(1),
  sizeId: z.string().min(1),
  isFeatured: z.boolean().default(false).optional(),
  isArchived: z.boolean().default(false).optional(),
});

// Remaining content of the component not included for brevity

export default ProductForm;

When attempting to create a new product in the database by submitting the form, the onSubmit function does not seem to be triggered. Despite adding console logs to verify if the function runs upon form submission, no output is observed. There are no indications of errors or issues in the console.

UPDATE: Upon further investigation, I implemented an onInvalid function in the submit process and encountered the following error message:

{image: {…}}
image
: {message: 'Required', type: 'invalid_type', ref: undefined}
[[Prototype]]
: Object
The error appears to be Zod-related, specifically indicating an "invalid_type". What could potentially be causing this issue within my code?

Answer №1

I suggest updating your formSchema based on the following guidelines:

const formSchema = z.object({
  // name: z.string().min(1), -- in prisma schema we have label and imageUrl, not a name.
  name: z.string().min(1),
  images: z.object({ url: z.string() }).array(),
  price: z.coerce.number().min(1),
  categoryId: z.string().min(1),
  colorId: z.string().min(1),
  sizeId: z.string().min(1),
  isFeatured: z.boolean().default(false).optional(),
  isArchived: z.boolean().default(false).optional(),
});

Modifications made:

  • Changed image to images

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

Connecting Ionic 3 with Android native code: A step-by-step guide

I just finished going through the tutorial on helpstack.io and was able to successfully set up the HelpStackExample with android native based on the instructions provided in the GitHub repository. The only issue is that my company project uses Ionic 3. H ...

I encountered a TypeScript error while utilizing the useContext hook in a React application

Initially, I set the value of createContext to an empty object {}. Afterwards, I provided a context with a new value of {username: 'sasuke1'}. However, when I attempt to access the property Context.username, TypeScript raises the following error: ...

While using Angular CLI on GitLab CI, an error occurred indicating that the custom rule directory "codelyzer" could not be

ng lint is throwing an error on Gitlab CI stating: An unhandled exception occurred: Failed to load /builds/trade-up/trade-up/common/projects/trade-up-common/tslint.json: Could not find custom rule directory: codelyzer. The strange thing is that ng lint ru ...

Enhancing the efficiency of Angular applications

My angular application is currently coded in a single app.module.ts file, containing all the components. However, I am facing issues with slow loading times. Is there a way to improve the load time of the application while keeping all the components within ...

Troubleshooting Nextjs App Directory: Issues with MDX & Link functionality and relative links

I posted this inquiry on the Next.js Github Issues page, but unfortunately did not receive any response. The code I am using is sourced from next.js/examples/app-dir-mdx. You can also find it in this codeSandbox. The only modification I made was: creatin ...

Discovering the power of chaining operators in RxJS 6 by encapsulating .map within

I am in the process of updating my Observable code from RXJS 5 to version 6. import { Injectable } from '@angular/core'; import { Observable } from 'rxjs' import { AppConfig } from '../config/app-config'; import { Xapi } from ...

Steps for connecting to a property in another component

As a newcomer to Angular, I am exploring new concepts for the first time. I have a custom component called Timeselector with an Apply button whose enable/disable state is determined by validations performed in another custom component called Monthpicker. C ...

Finding the percentage scores for five different subjects among a class

As a beginner in TypeScript, I am still learning the ropes. Here is the code snippet I used to calculate percentage: pere() { this.E=(((+this.English+ +this.Tamil+ +this.Maths+ +this.Science+ +this.Social)/500)*100); console.log(this.E); The result w ...

Tips for utilizing buttons with the antd framework in Visual Studio Code

When using the Button and Input components from antd in vscode, I encountered an error specifically with the Button component and I am curious to understand why it is happening. Interestingly, when I tried using the Input component, it did not show any er ...

I am attempting to retrieve the JSON object value from an error response while making a POST request in my Next.js application

Users can input an email into an input field, which is then sent as a post request to an API using the following code: try { const res = await fetch("/api/email-registration", { method: "POST", headers: { ...

Angular 4 Operator for adding elements to the front of an array and returning the updated array

I am searching for a solution in TypeScript that adds an element to the beginning of an array and returns the updated array. I am working with Angular and Redux, trying to write a reducer function that requires this specific functionality. Using unshift ...

Ways to determine if an optional parameter has been defined

One method I use to verify if the body property has been passed to the function. Is there a more straightforward approach in TypeScript? httpAPI<T>(httpMethod: HttpMethod, url: string, optional?: { params?: HttpParams, body?: any, isUseCache?:boole ...

Having trouble installing the gecko driver for running protractor test scripts on Firefox browser

Looking to expand my skills with the "Protractor tool", I've successfully run test scripts in the "Chrome" browser. Now, I'm ready to tackle running tests in "Firefox," but I know I need to install the "gecko driver." Can anyone guide me on how t ...

Using TypeScript with MongoDB aggregation

Recently, I've been working on a User model with the goal of achieving generic aggregation. Essentially, I want to be able to pass an array of objects to a function and have it execute smoothly. Let me provide you with a snippet of the getUser functi ...

When you import objects in Typescript, they may be undefined

I have a file called mock_event that serves as a template for creating an event object used in unit testing. Below, you can find the code snippet where this object is initialized: mock_event.ts import {Event} from "../../../models/src/event"; im ...

Challenges with passing props to a higher order stateless component in React using Typescript

I'm having trouble creating a NavLink following the react-router tutorial. I'm not sure why it's not working with Typescript 2.1 import React from 'react'; import { Link, LinkProps } from 'react-router'; const NavLink: ...

Collaborative service utilization in Angular 2

My goal is to create a shared service for my app. import { Injectable } from '@angular/core'; @Injectable() export class SharedService { testService() { console.log('share!'); } } However, when I attempt to inject this shared ...

Using Angular to make an API call within a JavaScript function

I am facing an issue when trying to call an API in a JavaScript function as shown below. The injected services (subService) and defined variables (formData) are not recognized in the JavaScript function, resulting in an error of undefined addSub. How can I ...

The onClick() handler within the map function is erroneously altering the state of every element rather than just the element that was clicked

Currently, I am working on a Next.js website that focuses on multiple choice questions (MCQs) and answers. Initially, only the questions are displayed with the title and options. There is a feature where a button allows users to reveal the answer to a sp ...

Guiding TypeScript to autonomously deduce the precise types of an object that implements a generic interface

Within this code snippet, TypeScript appears to be unaware of the specific type associated with userService.getByUserId in the final line. The expected type should be (userId: string) => ServiceResult<User>, but TypeScript is enforcing a more gene ...